问题描述
我想知道为什么我不能在另一个类(C ++ 11)的范围内用()而不是 {} ?错误:数字常数之前的预期标识符
I am wondering why I can't initialize an instance of the following template class with () instead of {} within the scope of another class (C++ 11)? error: expected identifier before numeric constant
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;
}
推荐答案
在,因为@TC提到的原因在注释部分:
Initializers using ()
were disallowed in the proposal of non-static data member initializers - N2756, for the reasons mentioned by @T.C. in the comment section:
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;
};
类似的解决方案是应用另一个现有规则,目前仅在模板中使用,是一个类型或
别的东西,那么它是别的东西;我们可以使用typename如果
我们真的意味着一个类型:
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
};
这两种解决方案都引入了许多用户可能会误解的微妙通过
comp.lang.c ++中的许多问题,关于为什么 int i();
在块范围不声明
default-已初始化 int
)。本文提出的解决方案是仅允许初始化器 =
initializer-clause 和 {
initializer-list
}
表单。
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 ++模板类,initialization()vs {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!