Nightmare Games
Nightmare Games

Reputation: 2435

Template class throwing error on non-parameterized constructors

I have a templated class with a parameterized constructor.

Here's a minimal example. The following code works fine:

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

What doesn't work is if I try using the default constructor.

Changing this line:

  my_template<int> int_thing (5);

To this:

  my_template<int> int_thing ();

Throws this error:

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  

On this line:

  int int_test = int_thing.get_value();

I haven't the foggiest. Removing the parameterized constructor from the class has no effect on the error thrown on the other constructor. C++ just hates that default constructor.

Theoretically, I can just throw some dummy data in the parameter and change it later, so it's not blocking me.

But I just have to know.

Upvotes: 2

Views: 96

Answers (1)

Oblivion
Oblivion

Reputation: 7374

This is a function declaration (see most vexing parse for details):

my_template<int> int_thing ();

You can simply use uniform initialization instead if you have > c++11:

my_template<int> int_thing {};

Otherwise just remove the parantheses.

Upvotes: 3

Related Questions