模板 class 在非参数化构造函数上抛出错误

Template class throwing error on non-parameterized constructors

我有一个带有参数化构造函数的模板化 class。

这是一个最小的例子。以下代码工作正常:

template <typename T>
class my_template
{
public:
    my_template () {}
    my_template (T Value) : value(Value) {}
    T get_value () { return value; }

private:
    int value;
};

int main()
{
    my_template<int> int_thing (5);
    my_template<char> char_thing ('a');

    int int_test = int_thing.get_value ();
    char char_test = char_thing.get_value ();
}

如果我尝试使用默认构造函数,那是行不通的。

更改此行:

  my_template<int> int_thing (5);

为此:

  my_template<int> int_thing ();

引发此错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0153   expression must have class type template_class  c:\Nightmare Games\Examples\CPP\template_class\template_class.cpp   39  

这一行:

  int int_test = int_thing.get_value();

我还不是最迷雾的。从 class 中删除参数化构造函数对在另一个构造函数上抛出的错误没有影响。 C++ 只是讨厌默认构造函数。

理论上,我可以在参数中放入一些虚拟数据,稍后更改它,所以它不会阻止我。

但我只是知道。

这是一个函数声明(详见most vexing parse):

my_template<int> int_thing ();

如果你有 > c++11:

,你可以简单地使用统一初始化
my_template<int> int_thing {};

否则只需删除括号。