Reputation: 15343
Lets say I have a function which takes a function pointer as a parameter, and that parameter has a default argument.
template <typename T>
T* default_construct()
{
return new T();
}
template <typename T>
void register(T* (*construct)() = default_construct<T>)
{
// Save that function pointer for later
}
Lets say I want to use register on my class Foo
, but Foo
doesn't have a default constructor, so my default_construct
won't work on it. The obvious solution is to do something like this:
Foo* construct_Foo()
{
return new Foo("String argument", 123);
}
SomeFunc()
{
// ...
register<Foo>(construct_Foo);
// ...
}
But that doesn't work. Even though register<Foo>
may only be called in one place, and it's passed a function to use, default_construct<Foo>
still gets instantiated by the compiler, and I get compiler errors. It seems like since it never gets used, it ought to be skipped over, but I guess that's not the case.
Is there any way to prevent default_construct
from being instantiated when it's being used as a default argument? The only solution I can think of is to put it in the template, but it seems like there ought to be a better solution.
Upvotes: 5
Views: 227
Reputation: 75150
Here's one solution that solves the problem because it doesn't use default arguments:
template <typename T>
T* default_construct()
{
return new T();
}
template <typename T>
void register(T* (*construct)())
{
// Save that function pointer for later
}
template<typename T>
void register()
{
register<T>(default_construct<T>);
}
Note that register
is a C++ keyword though :)
Upvotes: 6