So in writing a C++ template class, I have defined a method that returns an object of the templated type, as such:
template
class Foo
{
public
The line
T t;
Default constructs objects, yet declares uninitialized built-in types. There is no syntax to 'default construct' a local variable.
Therefore it's not trivial to write generic code that initializes a variable, whether built-in or class.
Wrapping the type into a member variable, however, may present a workaround that does not need copy construction (apart from the return statement):
template< typename T > struct Initializer {
T t;
Initializer()
:t() // ====> default construction, works for classes _and_ built-in
{}
};
Using this wrapper, you can build your code in a generic way:
template T foo() {
Initializer i;
// fill in i.t to your liking
return i.t;
}
See a full-blown snippet at codepad.