Metaprogramming with std::is_same

后端 未结 2 1388
广开言路
广开言路 2021-02-07 20:07

Is it possible to do something like the following that compiles without template specialization?

template  
class A {
public:
  #if std::is_same&l         


        
2条回答
  •  失恋的感觉
    2021-02-07 20:27

    Yes. Make the function templates and then conditionaly enable them using std::enable_if:

    #include 
    
    template  
    class A {
    public:
    
      template
      typename std::enable_if::value>::type
      has_int() {}
    
      template
      typename std::enable_if::value>::type
      has_char() {}
    };
    
    int main()
    {
        A 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. 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:

    std::enable_if_t::value>
    

    And C++17, even shorter:

    std::enable_if_t>
    

提交回复
热议问题