我很困惑为什么以下使用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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。