c++ - 整数到模板 : cannot appear in a constant-expression

标签 c++ templates

我从来没有做过模板编程。我需要的是:根据特定的整数(用户输入),我的模板应该确定一个类型。这是我的模板:

template<int T> struct abcd {};

template<>
struct abcd<6> { typedef double type_t; };
template<>
struct abcd<5> { typedef float type_t; };
template<>
struct abcd<0> { typedef unsigned char type_t; };enter code here

在某些功能中我想像这样使用我的模板:

void foo(int i, int m)
{
    const int j = i;
    // Assume elements of A can be accessed as A.at<dataType>(location)
    int a = A<abcd<j>::type_t>(m)
   //do something.. 
}

这显示错误 cannot appear in a constant-expression。请告诉我我做错了什么,什么是解决方案。请注意,如果我使用 const int j = 5 或任何其他相关的 int 而不是 const int j = i,它工作正常。这让我很困惑。

最佳答案

abcd<j>必须在编译时实例化,所以 j必须是常量表达式。在你的情况下,你不知道 j在编译时,因为它是从函数的参数中获得的 foo ,这就是错误的原因。

函数的参数不被视为常量表达式,即使您调用 foo(6,...) .参数6 ,虽然在编译时已知,但受限于参数 i , 它本身不是常量表达式。

虽然你可能有类似的东西

foo(constexpr i, int m)

但是这样的语法是不合法的,即函数参数不能是常量表达式。我不知道为什么标准不允许这样的构造,我非常愿意听到任何意见。

解决方法是声明 foo服用i作为模板,比如

template<int i>
void foo(int m)
{
    const int j = i;
    // now can use j as a constant expression
}

并调用它,例如

f<5>(...);

关于c++ - 整数到模板 : cannot appear in a constant-expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28179146/

相关文章:

templates - 错误: 'template' (as a disambiguator) is only allowed within templates

c++ - 如果在推演过程中无法解析函数的地址,是SFINAE还是编译器错误?

C++ 屏幕截图 - 如何读取位图?

c++ - 无效的用户定义转换 : C++ error

c++ - 使用 cat 命令合并由多个线程创建的文件是否有效?

c++ - 如何在 C++ 中用列表初始化对象?

c++ - 访问双指针导致段错误

c++ - 特征中静态成员的初始化

c++ - <未解析的重载函数类型>

c++ - 如何初始化模板类型以将 POD 数据归零或默认构造非 POD 数据?