如何将类型标识与模板一起使用



我试图通过检查传递到模板中的类型来提供更多的类型安全性。此外,这会影响计算中使用的常量(在本例中为机器-epsilon)

我的问题是在这种情况下typeid似乎发出一些奇怪的类型。

// compile with g++ -Wall -g -std=c++14
#include <typeinfo>
#include <iostream>
#include <limits>
#define MYFLOAT float
template <typename FLOAT_T>
const double mach_eps = std::numeric_limits<FLOAT_T>::epsilon();
double gamma(const std::type_info& float_t, long long int n)
{
double eps;
if (typeid(float_t) == typeid(double)) {
eps = mach_eps<double>;
} else if (typeid(float_t) == typeid(float)) {
eps = mach_eps<float>;
} else {
std::cerr << "gamma: unsupported floating-point type "
<< typeid(float_t).name() << std::endl;
std::cerr << "for example: " << typeid(float).name() << std::endl;
throw(1);
}
return n * eps / (1.0 - n * eps);
}
int main (void)
{
std::cout << "gamma = " << gamma(typeid(MYFLOAT), 1000LL) << std::endl;
}

我得到的输出是

gamma = gamma: unsupported floating-point type N10__cxxabiv123__fundamental_type_infoE
for example: f
terminate called after throwing an instance of 'int'

我的问题是:这是怎么回事?什么是基本类型?

您正在type_info&上调用typeid,这是您已经调用typeid的对象。解决方案是将条件替换为以下内容。

if (float_t == typeid(double)) {
eps = mach_eps<double>;
} else if (float_t == typeid(float)) {
eps = mach_eps<float>;
} else {
std::cerr << "gamma: unsupported floating-point type "
<< typeid(float_t).name() << std::endl;
std::cerr << "for example: " << typeid(float).name() << std::endl;
throw(1);
}

相关内容

最新更新