gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:49:58 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com