【发布时间】:2014-03-29 06:26:05
【问题描述】:
我想创建一个 C++ 模板函数,该函数具有不同的常量,这些常量会根据模板类型的选择在实现中使用。
#define FLOAT_EPSILON (0.000001f)
#define DOUBLE_EPSILON (0.00000000000001)
template <class T> void func(T params)
{
const T epsilon = ???? // either FLOAT_EPSILON or DOUBLE_EPSILON depending on T
// do some calculations using epsilon
}
template void func(float params);
template void func(double params);
虽然我想了一些半途而废的方法,但我不知道如何做到最好。你能帮忙吗?
【问题讨论】:
-
使用
std::numeric_limits怎么样? -
numeric_limits 看起来是一种可能性,尽管那时我正在使用预定义的值,而不是针对特定数值应用程序调整的我自己的值,尽管我想我可以适当地缩放它们并且接受给定的比率。
-
Denis,你能举个例子说明如何使用 decltype 来解决这个问题吗?
-
我发现
T my_epsilon = std::numeric_limits<T>::epsilon();效果很好。
标签: c++ templates types conditional constants