【发布时间】:2014-08-26 04:07:29
【问题描述】:
在这个简单的示例中,即使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
}
【问题讨论】:
标签: c++ templates c++11 constexpr c++14