c++ - 我对 enable_if 和 has_member 做错了什么?

标签 c++ templates template-meta-programming enable-if

我想我已经盯着这个看太久了,但我在这里找不到我的错误:

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/

相关文章:

c++ - 组织客户端-服务器游戏中的代码

c++ - 可变参数模板类中的多重继承和调用构造函数

c++ - 了解功能特征模板的工作原理。特别是,指向成员函数的指针是怎么处理的

c++ - 是否可以从函数模板返回可变参数 lambda?

c++ - 循环遍历容器作为模板

c++ - C++中指向成员函数的指针

C++ - 将右值引用传递给函数?

c++ - 将项目添加到双向链表的后面时遇到问题

来自模板参数的 C++ 通用模板方法名称

c++ - 可变参数模板调度器