作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 boost::enable_if 打开/关闭类模板中的某些函数,但总是出现编译错误 error: no type named "type"in struct boost::enable_if.
我的片段:
#include <iostream>
#include <tr1/type_traits>
#include <boost/utility.hpp>
namespace std {
using namespace tr1;
}
template <typename T1>
struct C {
template< typename T2 >
void test( T2&, typename boost::enable_if<
std::is_const< T1 >, T1 >::type* = 0 ) {
std::cout << "const" << std::endl;
}
template< typename T2 >
void test( T2&, typename boost::disable_if<
std::is_const< T1 >, T1 >::type* = 0 ) {
std::cout << "non-const" << std::endl;
}
};
int main() {
const int ci = 5;
int i = 6;
C<char> c;
c.test(ci);
c.test(i);
return 0;
}
但是下面类似的代码可以正常工作:
#include <iostream>
#include <tr1/type_traits>
#include <boost/utility.hpp>
namespace std {
using namespace tr1;
}
template <typename T1>
struct C {
template< typename T2 >
void test( T2&, typename boost::enable_if<
std::is_const< T2 >, T1 >::type* = 0 ) {
std::cout << "const" << std::endl;
}
template< typename T2 >
void test( T2&, typename boost::disable_if<
std::is_const< T2 >, T1 >::type* = 0 ) {
std::cout << "non-const" << std::endl;
}
};
int main() {
const int ci = 5;
int i = 6;
C<char> c;
c.test(ci);
c.test(i);
return 0;
}
我想要实现的是根据类模板中声明的类型禁用/启用一些成员函数。实际上不需要模板成员函数。它们仅为 SFINAE 添加。
谁能帮忙??
谢谢!
最佳答案
SFINAE (用于实现 enable_if
的机制)仅在函数模板的模板参数的上下文中起作用。在您的情况下, T1
是封闭类模板的模板参数,而不是函数模板本身的模板参数。从函数模板的角度来看,它是一个固定类型,不能按照声明中拼写的方式使用它是一个正常错误,而不是替换失败。
关于c++ - 如何在类模板中使用 boost::enable_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21425710/
我是一名优秀的程序员,十分优秀!