C++ 如何在类模板中使用boost::enable_
我试图使用boost::enable_if来打开/关闭类模板中的某些函数,但总是得到编译错误错误:在struct boost::enable_if中没有名为“type”的类型 我的片段:C++ 如何在类模板中使用boost::enable_,c++,templates,boost,enable-if,C++,Templates,Boost,Enable If,我试图使用boost::enable_if来打开/关闭类模板中的某些函数,但总是得到编译错误错误:在struct boost::enable_if中没有名为“type”的类型 我的片段: #include <iostream> #include <tr1/type_traits> #include <boost/utility.hpp> namespace std { using namespace tr1; } template <type
#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;
}
#包括
#包括
#包括
名称空间标准{
使用名称空间tr1;
}
样板
结构C{
模板
无效测试(T2&,typename boost::启用<
标准::is_const,T1>::类型*=0){
std::cout,T1>::type*=0){
std::cout,T1>::type*=0){
std::cout,T1>::type*=0){
std::cout(用于实现启用\u if
的机制)仅在函数模板的模板参数的上下文中有效。在您的情况下,T1
是封闭类模板的模板参数,而不是函数模板本身的模板参数。从函数模板的角度来看,它是固定类型,不能按声明中所述的方式使用它是正常错误,不是替换失败。(用于实现启用\u的机制,如果)仅在函数模板的模板参数的上下文中有效。在您的情况下,T1
是封闭类模板的模板参数,而不是函数模板本身的模板参数。从函数模板的角度来看,它是固定类型,不能按声明中所述的方式使用它是正常错误,不是替换失败。一种方法是对类本身进行专门化,如果您只想对某些函数执行此操作,则可能将其作为基类:
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> {
//...
};
模板
结构B{
样板
孔隙试验(T2&){
std::cout一种方法是对类本身进行专门化,如果您只想对某些函数执行此操作,则可能将其作为基类:
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> {
//...
};
模板
结构B{
样板
孔隙试验(T2&){
标准::cout