【问题标题】:What am I doing wrong with enable_if and has_member?enable_if 和 has_member 我做错了什么?
【发布时间】:2012-08-18 19:56:36
【问题描述】:

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

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>'

(注意,我真的喜欢here 中描述的这个测试的新 C++11 版本,但是 VS2012 还不支持 constexpr。)

【问题讨论】:

  • 为什么使用未命名的结构?
  • 哦,儿子……这是布尔值。对不起,伙计们,显然是一个愚蠢的问题。

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


【解决方案1】:

您的hasEmpty::empty 方法返回bool

struct 
{
    bool empty() const
    {
       return true;
    }
} hasEmpty;

但是您的 trait 使用返回 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> *);

这是为我编译的。

【讨论】:

  • 未命名的结构不是问题!
  • 叹息。就像我说的。我一定很累。谢谢。
猜你喜欢
  • 2011-06-01
  • 1970-01-01
  • 2012-02-17
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多