我想我已经盯着这个看太久了,但我在这里找不到我的错误:
struct
{
bool empty() const
{
return true;
}
} hasEmpty;
template<typename T>
struct has_empty
{
private:
template<typename U, U>
class check {};
template<typename C>
static char f(check<void (C::*)() const, &C::empty> *);
template<typename C>
static long f(...);
public:
static const bool value = (sizeof(f<T>(nullptr)) == sizeof(char));
};
template<typename T>
typename std::enable_if<has_empty<T>::value>::type foo(const T& t)
{
}
void x()
{
foo(hasEmpty);
}
Visual Studio 2012 报告:
error C2893: Failed to specialize function template 'std::enable_if<has_empty<T>::value>::type foo(const T &)'
1> With the following template arguments:
1> '<unnamed-type-hasEmpty>'
(请注意,我真的喜欢此测试的新 C++11 版本,如 here 所述,但 VS2012 尚不支持 constexpr。)
最佳答案
您的hasEmpty::empty
方法返回bool
:
struct
{
bool empty() const
{
return true;
}
} hasEmpty;
但您的特征使用返回 void
的成员函数指针,该替换将始终失败。你应该改变这个:
template<typename C>
ctatic char f(check<void (C::*)() const, &C::empty> *);
为此:
template<typename C>
static char f(check<bool (C::*)() const, &C::empty> *);
那是为我编译的。
关于c++ - 我对 enable_if 和 has_member 做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12021803/