[英]Integer to a template: cannot appear in a constant-expression
I never did template programming. 我从未做过模板编程。 What I need is the following: depending on certain integer (user input), my template should determine a type.
我需要以下内容:根据某些整数(用户输入),我的模板应确定类型。 Here is my template:
这是我的模板:
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
In certain function I want to use my template like this: 在某些功能中,我想像这样使用模板:
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..
}
This is showing error cannot appear in a constant-expression
. 这表明错误
cannot appear in a constant-expression
。 Please tell me what I am doing wrong and what can be a solution. 请告诉我我做错了什么,什么可以解决。 Note that if I put
const int j = 5
or any other relevant int
instead of const int j = i
, it is working fine. 请注意,如果我将
const int j = 5
或任何其他相关int
代替const int j = i
,则可以正常工作。 That is confusing me. 那使我感到困惑。
abcd<j>
has to be instantiated at compile time, so j
has to be a constant expression. abcd<j>
必须在编译时实例化,因此j
必须是一个常量表达式。 In your case, you don't know j
at compile time, since it is obtained from the parameter of the function foo
, and that's why the error. 在您的情况下,您在编译时不知道
j
,因为它是从函数foo
的参数获得的,这就是为什么会出错。
Parameters of a function are not considered constant expressions, even if you invoke foo(6,...)
. 即使调用
foo(6,...)
,也不foo(6,...)
函数的参数视为常量表达式。 The argument 6
, although known at compile time, is bounded to the parameter i
, which is NOT by itself a constant expression. 尽管参数
6
在编译时是已知的,但它与参数i
绑定,而参数i
本身不是常数表达式。
You may have though that you have something like 虽然您可能会遇到类似
foo(constexpr i, int m)
but such syntax is illegal, that is, function parameters cannot be constant expressions. 但是这种语法是非法的,也就是说,函数参数不能是常量表达式。 I do not know exactly why the standard does not allow such constructions, and I'm more than willing to hear any opinions.
我不确切知道为什么该标准不允许这种构造,我非常愿意听到任何意见。
A workaround is to declare foo
taking i
as a template, like 一种解决方法是声明
foo
以i
作为模板,例如
template<int i>
void foo(int m)
{
const int j = i;
// now can use j as a constant expression
}
and invoke it as eg 并调用它例如
f<5>(...);
在编译期间必须知道j的值。
Please note that template parameters need to be known at compile time . 请注意,在编译时需要知道模板参数。 You've declared
j
as a constant, but it is not known at compile time 您已将
j
声明为常量,但在编译时未知
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.