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

标签 c++ templates c++11

我想知道为什么我不能在另一个类 (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/

相关文章:

c++ - 为什么不从构造函数中推断模板参数?

c++ - 在差异进程的线程之间发送信号

c++ - C++中用于搜索字符串模式的正则表达式

c++ - 从 UnicodeString 创建 CData 节点时的 XML 无效字符

c++ - 为什么 insert_or_assign 没有迭代器重载?

c++ - 此错误会导致什么 C++ 模板问题?

c++ - c++ 概念是否会导致编写模板实例以构建输出?

wpf - 重新定义控件模板时依赖属性从何而来?

performance - C++ - 最快的双线性插值?

c++ - 使一个类或结构成为所有模板实例化类的 friend ?