gpt4 book ai didi

c++模板类,初始化() vs {}

转载 作者:太空狗 更新时间:2023-10-29 20:03:17 25 4
gpt4 key购买 nike

我想知道为什么我不能在另一个类 (C++ 11) 的范围内使用 () 而不是 {} 来初始化以下模板类的实例?错误:数字常量之前的预期标识符

template <typename T>
class vec3 {

private:

T data[3];

public:

vec3 (T a, T b, T c);
};

template <typename T>
vec3<T>::vec3 (T a, T b, T c)
{
data[0] = a;
data[1] = b;
data[2] = c;
}

class whatever {

vec3 <float> a (1,2,3); // not ok
vec3 <float> b {1,2,3}; // ok

};

int main () {

vec3 <float> a (1,2,3); // ok

return 0;
}

最佳答案

proposal of non-static data member initializers - N2756 中不允许使用 () 的初始化程序,出于@T.C.提到的原因。在评论区:

Unfortunately, this makes initializers of the “( expression-list )” form ambiguous at the time that the declaration is being parsed:

struct S {
int i(x); // data member with initializer
// ...
static int x;
};

struct T {
int i(x); // member function declaration
// ...
typedef int x;
};

One possible solution is to rely on the existing rule that, if a declaration could be an object or a function, then it’s a function:

struct S {
int i(j); // ill-formed...parsed as a member function,
// type j looked up but not found
// ...
static int j;
};

A similar solution would be to apply another existing rule, currently used only in templates, that if T could be a type or something else, then it’s something else; and we can use “typename” if we really mean a type:

struct S {
int i(x); // unabmiguously a data member
int j(typename y); // unabmiguously a member function
};

Both of those solutions introduce subtleties that are likely to be misunderstood by many users (as evidenced by the many questions on comp.lang.c++ about why “int i();” at block scope doesn’t declare a default-initialized int). The solution proposed in this paper is to allow only initializers of the “= initializer-clause” and “{ initializer-list }” forms.

关于c++模板类,初始化() vs {},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196754/

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