加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用std :: is_same进行元编程

发布时间:2020-12-16 05:57:00 所属栏目:百科 来源:网络整理
导读:是否可以执行以下编译而无需模板专业化的操作? template class T class A {public: #if std::is_sameT,int void has_int() {} #elif std::is_sameT,char void has_char() {} #endif};Aint a; a.has_int();Achar b; b.has_char(); 解决方法 是.制作功能模板,
是否可以执行以下编译而无需模板专业化的操作?
template <class T> 
class A {
public:
  #if std::is_same<T,int>
  void has_int() {}
  #elif std::is_same<T,char>
  void has_char() {}
  #endif
};
A<int> a; a.has_int();
A<char> b; b.has_char();

解决方法

是.制作功能模板,然后使用 std::enable_if条件启用它们:
#include <type_traits>

template <class T> 
class A {
public:

  template<typename U = T>
  typename std::enable_if<std::is_same<U,int>::value>::type
  has_int() {}

  template<typename U = T>
  typename std::enable_if<std::is_same<U,char>::value>::type
  has_char() {}
};

int main()
{
    A<int> a;
    a.has_int();   // OK
    // a.has_char();  // error
}

如果类很大并且有许多函数需要与T无关,那么the other answer的解决方案可能不可行.但是你可以通过继承另一个仅用于这些特殊方法的类来解决这个问题.然后,您只能专门化该基类.

在C 14中,有方便的类型别名,因此语法可以变为:

std::enable_if_t<std::is_same<U,int>::value>

而C 17甚至更短:

std::enable_if_t<std::is_same_v<U,int>>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读