【发布时间】:2017-07-02 13:28:20
【问题描述】:
我正在尝试使用模板编写“强大”功能。
#define VAR_X 2.0f
template <int N> struct Power
{
static const float ret = VAR_X * Power<N-1>::ret;
};
template <> struct Power<0>
{
static const float ret = 1.0f;
};
我为变量使用了宏,因为浮点数不能用作模板参数。当我尝试用 g++ 5.4.0 编译时,我得到了这个:
tmptrig.cpp: In instantiation of ‘const float Power<1>::ret’:
tmptrig.cpp:35:28: required from here
tmptrig.cpp:17:24: error: the value of ‘Power<0>::ret’ is not usable in a constant expression
static const float ret = VAR_X * Power<N-1>::ret;
^
tmptrig.cpp:22:24: note: ‘Power<0>::ret’ does not have integral or enumeration type
static const float ret = 1.0f;
但是,当我将程序更改为仅处理整数时,它可以正常工作。
#define VAR_X 2
template <int N> struct Power
{
static const int ret = VAR_X * Power<N-1>::ret;
};
template <> struct Power<0>
{
static const int ret = 1;
};
我知道浮点数不能用作模板参数,但(据我所知)这里不是这样对待它们的。为什么我使用浮点数时编译器不喜欢它?
编辑:这就是我的main 的样子:
int main(int argc, char *argv[])
{
std::cout << Power<1>::ret << std::endl;
}
【问题讨论】:
-
将
const更改为constexpr。 -
这里使用宏完全没有帮助。宏只是在文本上被替换:它仍然是一个浮点数(因此是错误)。
标签: c++ templates floating-point template-meta-programming