给定:
struct A
{
virtual bool what() = 0;
};
template<typename T, typename Q>
struct B : public A
{
virtual bool what();
};我想部分专门化what,如下所示:
template<typename T, typename Q>
bool B<T, Q>::what()
{
return true;
}
template<typename Q>
bool B<float, Q>::what()
{
return false;
}但这似乎是不可能的(是在C++11中吗?)所以我试了试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 thread,结果是:
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;
}
};这个最终的解决方案可以工作,但是为什么enable_if技术不能工作呢?我也非常愿意接受我还没有遇到过的更清晰的答案的建议。
我尽可能地简化了我的示例--在我的实际用例中,what()不叫what,实际上做了相当多的工作,我想“专攻”一个用户定义的类型,而不是float。
https://stackoverflow.com/questions/10284498
复制相似问题