Given:
struct A
{
virtual bool what() = 0;
};
template<typename T, typename Q>
struct B : public A
{
virtual bool what();
};
I want to partially specialize what
like:
template<typename T, typename Q>
bool B<T, Q>::what()
{
return true;
}
template<typename Q>
bool B<float, Q>::what()
{
return false;
}
But it appears that this isn't possible (is it in C++11?) so I tried SFINAE:
template<typename T>
typename std::enable_if<std::is_same<T, float>::value, bool>::type B<T>::what()
{
return true;
}
template<typename T>
typename std::enable_if<!std::is_same<T, float>::value, bool>::type B<T>::what()
{
return false;
}
This also doesn't work, I have no idea why though, does anyone? So I found this thread and ended up with:
template<typename T, typename Q>
struct B : public A
{
virtual bool what()
{
return whatimpl(std::is_same<T, float>());
}
bool whatimpl(std::false_type)
{
return false;
}
bool whatimpl(std::true_type)
{
return true;
}
};
This final solution works, but why doesn't the enable_if
technique work? I'm also very open to suggestions of a cleaner answer that I haven't encountered yet.
I simplified my examples as much as possible - in my real use case what()
isn't called what and actually does a fair bit of work, and I'll want to 'specialize' on a user defined type, not float
.
template<> bool B<float, float>::what() { return false; }
– Greenleaf