I had a similar issue. In my case, I just had a situation where I wanted to initialize a variable of the template parameter type, not as a default return. I could not get any of the above methods to work. I used a variation on @jfMR's suggestion. (Posting as a separate answer for formatting). In my case, I also wanted to support both primitive types and object types.
I used a second template parameter to provide a callable struct producing the default value I need. Full sample:
#include <stdio.h>
#include <string>
#include <iostream>
struct DefaultInt
{
int operator () () const { return 42; }
};
struct DefaultChar
{
char operator () () const { return 'z'; }
};
struct DefaultString
{
std::string operator () () const { return std::string("waldo"); }
};
template<class TP, class TPDefaultValue> class DemoWrapper
{
public:
DemoWrapper()
{
TPDefaultValue valueFactory;
_wrap = valueFactory();
}
DemoWrapper(TP wrap) : _wrap(wrap)
{}
void Print() { std::cout << _wrap << std::endl; }
private:
TP _wrap;
};
int main(int argc, const char *argv[])
{
std::string demoString("Thanks for all the fish");
const int demoInt = 13;
DemoWrapper<int, DefaultInt> dw1(demoInt);
DemoWrapper<int, DefaultInt> dw2;
DemoWrapper<std::string, DefaultString> dw3(demoString);
DemoWrapper<std::string, DefaultString> dw4;
dw1.Print();
dw2.Print();
dw3.Print();
dw4.Print();
}
Output:
13
42
Thanks for all the fish
waldo