Reputation: 10808
I have the following method defined:
template <typename Interface>
Interface Create();
with this implementation:
template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type Create()
{
...
}
but now I get the following errors: "undefined reference to ITestInterface* Create()"
when I remove the std::enable_if
, everything works fine. But I require it to work since I want to add versions of this function that work when Interface is a reference or when Interface is a std::vector
. What am I doing wrong here? I also noticed that this is a linker error - but I don't know why. Can someone give me a hint?
Upvotes: 2
Views: 1121
Reputation: 217145
Whereas in normal function, return type doesn't be part of signature,
return type does be part of signature for template function.
So
template <typename Interface> Interface Create();
differs than
template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type
Create();
You have to use same signature in declaration and definition.
As partial specialization is not possible on function, you have to use helper class: Something like may help:
namespace detail
{
template <typename > struct CreateHelper;
template <typename T> struct CreateHelper<T*>
{
static T* create() {
// Implementation with T*
}
};
template <typename T> struct CreateHelper<T&>
{
static T& create() {
// Implementation with T&
}
};
template <typename T> struct CreateHelper<std::vector<T>>
{
static std::vector<T> create() {
// Implementation with std::vector<T>
}
};
} // namespace detail
template <typename Interface> Interface Create()
{
return detail::CreateHelper<Interface>::create();
}
Upvotes: 3