Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

template code declared outside of class doesn't compile

I want to declare the constructor outside of the class but there is something wrong with the template code.

template <size_t size = 1>
class my_class
{
public:
    template <class int_t>
    constexpr my_class(int_t);
};

template<class int_t, size_t size>
constexpr my_class<size>::my_class(int_t num)
{

}

but this works:

template <size_t size = 1>
class my_class
{
public:
    template <class int_t>
    constexpr my_class(int_t) {};
};

or:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template <size_t size = 1>
class my_class
{
public:
    constexpr my_class();
};

template<size_t size>
constexpr my_class<size>::my_class()
{

}

I have no idea why this doesn’t work.
I asked ChatGPT but it told me that there is no error?

>Solution :

The my_class constructor function is a template inside a template. You can’t combine templates inside templates as a single template, especially not in the wrong order.

You need two template declarations:

template<size_t size>
template<typename int_t>
constexpr my_class<size>::my_class(int_t num)
{

}

Please note that the order of the templates matters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading