3

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?

DawidPi
  • 2,285
  • 2
  • 19
  • 41
  • http://stackoverflow.com/questions/2447458/default-template-arguments-for-function-templates – Lingxi Nov 27 '15 at 16:14

1 Answers1

5
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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Yeah I know in fact, that It works, but it does not compile on msvc 2012 as there I cannot have default template types on class's members. What then? – DawidPi Nov 27 '15 at 16:20
  • @DawidPi create 4 overloads, with near-exact duplicates of the body and initializer list, each taking 1 2 3 and 4 arguments? Get a new compiler? – Yakk - Adam Nevraumont Nov 27 '15 at 16:25
  • That's the way I do this now in fact :) But I have 9 argument function, so you can just imagine how ugly code, becomes. Of course getting new compiler for whole company is impossible for me :) but still thanks :) – DawidPi Nov 27 '15 at 16:28
  • 1
    @DawidPi Boost has macros that they used to emulate variardics. You could also write a function object (not a template function, because you cannot pass those around, and not a function, because they cannot represent more than 1 overload) and create an adapter that makes it variardic (writing the above 9+ overloads, dispatching more/fewer `none_t`s to the function object depending on passed-in arguments) if you find yourself doing it more than once. – Yakk - Adam Nevraumont Nov 27 '15 at 18:23