DawidPi
DawidPi

Reputation: 2365

C++ template constructor default arguments

In a very simple way. We have following code:

struct templateTest{
    struct {}m_none;
    template <typename T1, typename T2, typename T3, typename T4>
    templateTest(T1 arg1, T2 arg2=m_none, T3 arg3=m_none, T4 arg4=m_none){

    }
};

struct nonTemplate{
    nonTemplate(int arg1, int arg2=2, int arg3=3){}
};

int main()
{
    nonTemplate(5);
    nonTemplate(5,10);

    templateTest test2(5,10);
    templateTest test1(5);


    return 0;
}

What I would like to have is default constructor arguments in template class.

Default arguments work perfectly fine with nonTemplate class, but it's not that way with templateTest type. Error I have are following:

C2660: 'templateTest::templateTest' : function does not take 2 arguments

for constructor called with 2 arguments

And for constructor called with one argument compiler wants to invoke copyConstructor and output is following:

C2664: 'templateTest::templateTest(const templateTest &)' : cannot convert argument 1 from 'int' to 'const templateTest &'

Is there any way to achieve what I want on old C++ compilers, like msvc 2011?

Upvotes: 3

Views: 2147

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275896

struct none_t {};
template <class T1, class T2=none_t, class T3=none_t, class T4=none_t>
templateTest(T1 arg1, T2 arg2=none_t{}, T3 arg3=none_t{}, T4 arg4=none_t{}){

}

you cannot deduce the template type arguments from the default arguments. In essence, the template type arguments are deduced before default arguments are substituted.

live example.

Upvotes: 5

Related Questions