简体   繁体   English

使用std :: is_same进行元编程

[英]Metaprogramming with std::is_same

Is it possible to do something like the following that compiles without template specialization? 是否可以执行以下编译而无需模板专业化的操作?

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();

Yes. 是。 Make the function templates and then conditionaly enable them using std::enable_if : 制作函数模板,然后使用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
}

The solution from the other answer might not be feasible if the class is big and has got many functions that need to regardless of T . 如果类很大并且有许多函数需要与T无关, 那么另一个答案的解决方案可能不可行。 But you can solve this by inheriting from another class that is used only for these special methods. 但是你可以通过继承另一个只用于这些特殊方法的类来解决这个问题。 Then, you can specialize that base class only. 然后,您只能专门化该基类。

In C++14, there are convenient type aliases so the syntax can become: 在C ++ 14中,有方便的类型别名,因此语法可以变为:

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

And C++17, even shorter: 和C ++ 17,甚至更短:

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

Yes, with template specialization : 是的,使用模板专业化:

template <class T> 
class A;

template <> 
class A<int>
{
    void had_int(){}
};

template <> 
class A<char>
{
    void had_char(){}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM