Is there a way to use the Named Constructor Idiom with templates in a “pretty” fashion?
For instance:
#include <vector>
using namespace std;
template< typename T >
class Foo
{
public:
static Foo Copy(const T& arg)
{
Foo ret;
ret.t_copy = arg;
return ret;
}
static Foo CopyClear(const T& arg)
{
Foo ret;
ret.t_copy = arg;
ret.t_copy.clear();
return ret;
}
private:
T t_copy;
};
int main( int argc, char** argv )
{
vector<double> vec;
vec.push_back(1);
// #1: won't compile
Foo< vector<double> > a_foo = Foo::CopyClear( vec );
// #2: ugly, but works
Foo< vector<double> > a_foo = Foo< vector<double> >::CopyClear( vec );
return 0;
}
I’d like to use the syntax of #1 somehow. #2 works but rubs my DRY sense the wrong way.
EDIT: New, more “realistic” version of Foo.
EDIT2: No C++0x/C++1x for me I’m afraid 🙁
Updated answer
If I understand your intent correctly, this will do the trick:
This then compiles: