作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从来没有做过模板编程。我需要的是:根据特定的整数(用户输入),我的模板应该确定一个类型。这是我的模板:
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/
我是一名优秀的程序员,十分优秀!