微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

是否可以执行以下编译而无需模板专业化的操作?
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>>

原文地址:https://www.jb51.cc/c/113235.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐