如何使这个提升::enable_if代码编译(SFINAE)

How to make this boost::enable_if code compile (SFINAE)?

本文关键字:代码 编译 SFINAE if enable 何使这      更新时间:2023-10-16

我很困惑为什么以下使用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常量的类型。您需要的是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();
}

这样可以编译并运行良好。

在提升文档中的第 2 段下也有解释。

这里

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();
}
到目前为止

,我还没有使用enable_if,但也许

typename boost::enable_if<has_hello<T>>::type* = 0