[英]how to use boost::enable_if in class template
I am trying to use the boost::enable_if to turn on/off some functions in the class template but always get the compilation error error: no type named "type" in struct boost::enable_if . 我正在尝试使用boost :: enable_if来打开/关闭类模板中的某些功能,但始终会收到编译错误错误:struct boost :: enable_if中没有名为“ type”的类型 。
My snippet: 我的片段:
#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;
}
But the following similar codes work fine: 但是以下类似代码可以正常工作:
#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;
}
What I want to achieve is to disable/enable some member functions based the types declared in the class template. 我要实现的是基于类模板中声明的类型来禁用/启用某些成员函数。 Actually the template member function is not needed.
实际上,不需要模板成员函数。 They're only added for SFINAE.
仅为SFINAE添加了它们。
Anyone can help?? 任何人都可以帮忙吗?
Thanks! 谢谢!
SFINAE (which the mechanism used to implement enable_if
) only works in context of the function template's template parameters. SFINAE (用于实现
enable_if
的机制)仅在功能模板的模板参数的上下文中起作用。 In your case, T1
is a template parameter of the enclosing class template, not of the function template itself. 在您的情况下,
T1
是封闭类模板的模板参数,而不是功能模板本身的模板参数。 From the function template's point of view, it's a fixed type and not being able to use it the way it's spelled out in the declaration is a normal error, not a substitution failure. 从功能模板的角度来看,它是固定类型,不能按照声明中的拼写方式使用它是正常错误,而不是替代失败。
One way would be a specialization of the class itself, possibly as a base class in case you only want to do this for some functions: 一种方法是类本身的专用化,如果您只想对某些功能执行此操作,则可以将其作为基类:
template <typename T1>
struct B {
template<typename T2>
void test( T2& ) {
std::cout << "non-const" << std::endl;
}
};
template <typename T1>
struct B< const T1 > {
template<typename T2>
void test( T2& ) {
std::cout << "const" << std::endl;
}
};
template <typename T1>
struct C : B<T1> {
//...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.