3

我很困惑为什么以下使用的代码boost::enable_if无法编译。它检查 typeT是否有成员函数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错了吗?

4

3 回答 3

4

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

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

编译并运行良好。

也在boost 文档的第 2 段中解释。

于 2012-08-19T17:58:10.280 回答
3

这里

typename has_hello<T>::value

has_hello<T>::value不是类型名称。这是价值。


不确定bost,但以下工作(gcc 4.7 std=c++0x):

template<typename T>
void doSomething(T const& t,
                 typename std::enable_if<has_hello<T>::value>::type* = 0
                 ) {
  return t.hello();
}
于 2012-08-19T17:55:21.677 回答
2

到目前为止,我还没有使用 enable_if,但也许

typename boost::enable_if<has_hello<T>>::type* = 0
于 2012-08-19T17:53:49.373 回答