【问题标题】:how to use boost::enable_if in class template如何在类模板中使用 boost::enable_if
【发布时间】:2014-01-29 08:27:57
【问题描述】:

我正在尝试使用 boost::enable_if 来打开/关闭类模板中的某些功能,但总是得到编译错误 error: no type named "type" in struct boost::enable_if.

我的sn-p:

#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 添加的。

有人可以帮忙吗??

谢谢!

【问题讨论】:

    标签: c++ templates boost enable-if


    【解决方案1】:

    SFINAE(用于实现enable_if 的机制)仅在函数模板的模板参数的上下文中有效。在您的情况下,T1 是封闭类模板的模板参数,而不是函数模板本身的模板参数。从函数模板的角度来看,它是一个固定类型,不能按照声明中的说明使用它是正常错误,而不是替换失败。

    【讨论】:

      【解决方案2】:

      一种方法是对类本身进行专门化,可能作为基类,以防您只想为一些函数这样做:

      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> {
          //...
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多