如何使这个提升::enable_if代码编译(SFINAE)
How to make this boost::enable_if code compile (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
确实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
相关文章:
- 如何修复sfml c++代码编译错误
- 尝试用java代码编译和运行c++代码
- 此代码编译良好,但文件未创建?请指出错误
- 为什么我的 BaseClass:Method 代码编译(带有单冒号)?
- 代码编译没有任何输出,入门程序
- 通过Python Distutils(用于Python C扩展)使用可重定位的设备代码编译CUDA代码
- 代码编译但不起作用!cmd窗口只是理想和理想,但什么也没发生
- 无法使用 g++ 使用C++代码编译 C 库
- 如何在Ubuntu中使用Visual Studio代码编译C++代码
- 推力+提升代码编译错误
- C++代码编译,但在 Zorin OS 上运行时显示错误
- 如何在使用模板时将 CPP 代码编译到库文件中
- 是否可以将Visual Studio 2017将C 代码编译到EXE以外的文件类型中
- 使用 Visual Studio for C++ 代码编译错误
- 使用 Android Studio 使用本机代码编译 apk 时,如何在链接处删除 libgnustl_static.
- 使用 Emscripten 将 OpenCV 代码编译C++ Javascript
- 将C 代码编译到独立应用程序.App
- 为什么此代码编译 (C++11) 而没有类型不匹配错误
- 重用编译器前端的结果,以加快多个配置/平台的C++代码编译
- 如何将C++11代码编译为网络汇编