在这个简单的例子中,即使
test1
成功通过编译,但是 test2
无法通过编译,我不知道为什么会出现这种情况。如果 arr[i]
适合作为一个被标记为 constexpr
的函数的返回值,那么它为什么不能作为非类型模板参数呢?template<char c>
struct t
{
static const char value = c;
};
template <unsigned N>
constexpr char test1(const char (&arr)[N], unsigned i)
{
return arr[i];
}
template <unsigned N>
constexpr char test2(const char (&arr)[N], unsigned i)
{
return t<arr[i]>::value;
}
int main()
{
char a = test1("Test", 0); //Compiles OK
char b = test2("Test", 0); //error: non-type template argument
//is not a constant expression
}
编辑:这没有任何影响:
template<char c>
struct t
{
static const char value = c;
};
template <unsigned N>
constexpr char test1(const char (&arr)[N])
{
return arr[0];
}
template <unsigned N>
constexpr char test2(const char (&arr)[N])
{
return t<arr[0]>::value;
}
int main()
{
char a = test1("Test"); //Compiles OK
char b = test2("Test"); //error: non-type template argument
//is not a constant expression
}
test2
中删除unsigned i
,并改为使用arr[0]
作为索引,你仍然会得到相同的编译错误。 - Chris_Ft<test1(arr,i)>::value
,请查看编译器的输出。显然,在这种情况下test1不是constexpr,因为arr
和i
通常是运行时参数。该函数必须编译无论它们是字面量还是其他类型。 - Uselessconstexpr
的lambda表达式是我更希望实现的东西。 - TemplateRex