Search code examples
c++templatesinstantiation

"No Matching Constructor" Error When Trying to Instantiate Object of a Template Class


Edit:

  1. I am so sorry about the this and the lack of a ; at the end of my template class; I had some issues copying and pasting my code, so I copied some code by hand and messed those parts up.
  2. After reopening the IDE, the error just magically vanished. Maybe Repl.it was having some issues. The error message is different now. If I am unable to solve this error on my own, I will ask a new question.

Thank you to HugoTeixeira, Matthew Fisher, and user4581301 for your thoughtful responses.


I have the following code in Group.h:

template <typename T, int N> class Group
{
    public:
        T values[N];

        Group(T args[])
        {
            for (int i = 0; i < N; i++)
            {
                values[i] = args[i];
            }
        }

        Group()
        {
            Group((T[]){0, 0, 0});
        }
};

and in main.cpp, I have this code:

#include "Group.h"

int main()
{
    Group<double, 3> * v1 = new Group<double, 3>();
}

When I try to run this code, my IDE gives me the error:

no matching constructor for initialization of 'Group<double, 3>'

I have tried writing this code but minus the template, and it worked fine. What am I doing wrong?


Solution

  • There are a few issues with your code:

    Calling another constructor: If you want to call another constructor in C++, you cannot use the this keyword (like in Java). You have to do it after a colon (aka initializer list), like this:

    Group(): Group((T[]){0, 0, 0})
    {} 
    

    Class definitions end with a semi-colon: In C++, a class definition (templated or not) must end with a semi-colon. You forgot do add it to your code:

    class A {
        ...
    };  <<--- end with a semi-colon
    

    Raw pointers: Ideally your code shouldn't use raw pointers. There are smart pointers that can make your code more elegant and easier to maintain. You could, for example, use a std::unique_ptr or std::shared_ptr (depending on the case). Here is a simple example in C++14:

    auto v1 = std::make_unique<Group<double, 3>>();