gpt4 book ai didi

c++ - 模板值 `defValue' 不能出现在常量表达式中

转载 作者:太空狗 更新时间:2023-10-29 22:52:42 25 4
gpt4 key购买 nike

据我了解,模板值需要在编译时知道。所以我写了一个小例子只是为了看看我明白了,但显然我没有。所以我明白了:

`defValue' cannot appear in a constant-
expression

谁能问问这是什么问题以及如何解决?

#include <iostream>
template <class T,T defaultVal, int dim=255>
class Vec
{
T _vec[dim];
int _dim;
public:
Vec () : _dim(dim)
{
for (int i=0;i<_dim;++i)
{
_vec[i] = defaultVal;
}
}
~Vec () {};
// other operators and stuff
};

int main ()
{
int defValue = 0;
Vec < int,defValue > vecWithDefVal;// here is the problem but i don't know why
}

最佳答案

C++03 14.3.2

Template non-type arguments

A template-argument for a non-type, non-template template-parameter shall be one of:

— an integral constant-expression of integral or enumeration type; or

— the name of a non-type template-parameter; or

— the address of an object or function with external linkage, including function templates and functiontemplate-ids but excluding non-static class members, expressed as & id-expression where the & isoptional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or— a pointer to member expressed as described in 5.3.1 .

defValue [作为非类型参数] 不是以上任何一种。

更改 int defValue = 0;const int defValue = 0并且您的代码将编译 [参见第一个条件]。

或者直接写Vec <int,0> vecWithDefVal;

关于c++ - 模板值 `defValue' 不能出现在常量表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3845229/

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