【问题标题】:Template class throwing error on non-parameterized constructors模板类在非参数化构造函数上抛出错误
【发布时间】:2020-03-16 23:03:20
【问题描述】:

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

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

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();

我没有最迷糊的。从类中删除参数化构造函数对另一个构造函数引发的错误没有影响。 C++ 就是讨厌那个默认构造函数。

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

但我只是必须知道。

【问题讨论】:

    标签: c++ constructor most-vexing-parse parameterized-constructor


    【解决方案1】:

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

    my_template<int> int_thing ();
    

    如果你有> c++11,你可以简单地使用统一初始化:

    my_template<int> int_thing {};
    

    否则,只需删除括号即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多