c++ - 如何使这个 boost::enable_if 代码编译(SFINAE)?

标签 c++ boost sfinae enable-if

我很困惑为什么下面的代码使用了boost::enable_if不编译。它检查类型是否 T有一个成员函数 hello如果是这种情况,则调用它:

#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <boost/static_assert.hpp>

// Has_hello<T>::value is true if T has a hello function.
template<typename T>
struct has_hello {
  typedef char yes[1];
  typedef char no [2];
  template <typename U> struct type_check;
  template <typename U> static yes &chk(type_check<char[sizeof(&U::hello)]> *);
  template <typename  > static no  &chk(...);
  static const bool value = sizeof(chk<T>(0)) == sizeof(yes);
};

template<typename T>
void doSomething(T const& t,
                 typename boost::enable_if<typename has_hello<T>::value>::type* = 0
                 ) {
  return t.hello();
}

// Would need another doSomething` for types that don't have hello().

struct Foo {
  void hello() const {
    std::cout << "hello" << std::endl;
  }
};

// This check is ok:
BOOST_STATIC_ASSERT(has_hello<Foo>::value);

int main() {
  Foo foo;
  doSomething<Foo>(foo);
}

我得到了

no matching function for call to ‘doSomething(Foo&)

gcc 4.4.4 .

静态断言没问题,所以has_hello<Foo>::value确实是true .我在使用 boost::enable_if 吗?错了吗?

最佳答案

boost::enable_if 的第一个参数必须是一个类型,包含一个名为value 的静态bool 常量.您需要的是采用非类型 bool 参数的 enable_if_c 模板(注意 _c 后缀)。

template<typename T>
void doSomething(T const& t,
                 typename boost::enable_if_c<has_hello<T>::value>::type* = 0
                 ) {
  return t.hello();
}

compiles and runs很好。

也在 Paragraph 2 in boost docs. 下解释

关于c++ - 如何使这个 boost::enable_if 代码编译(SFINAE)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12028527/

相关文章:

c++ - 如何确定按下了键盘上的哪个键? C++

c++ - 指向指针 vector 的指针的内存消耗

c++ - boost 与标准原子顺序一致性语义

python - C++ Python Boost 中的友元函数

c++ - 没有enable_if 的表达式SFINAE?

c++ - 检查 Char 中的空格和检查字符串中的数字

c++ - 在结构中存储 COM 指针

unit-testing - boost 测试 : How to write parameterized test cases

c++ - 类成员重载方法的 SFINAE

c++ - 使用类型特征的部分类特化