c – 如何使这个boost :: enable_if代码编译(SFINAE)?
作者:互联网
我很困惑为什么以下使用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确实是真的.我使用boost :: enable_if错了吗?
解决方法:
boost :: enable_if的第一个参数必须是包含名为value的静态bool常量的类型.你需要的是enable_if_c模板(注意_c后缀),它采用非类型的bool参数.
template<typename T>
void doSomething(T const& t,
typename boost::enable_if_c<has_hello<T>::value>::type* = 0
) {
return t.hello();
}
也在Paragraph 2 in boost docs.下解释
标签:c,boost,sfinae,enable-if 来源: https://codeday.me/bug/20190723/1512036.html