What is the meaning of template<> with empty angle brackets in C++?

后端 未结 3 1868
悲哀的现实
悲哀的现实 2020-12-04 19:33
template<>
class A{
//some class data
};

I have seen this kind of code many times. what is the use of template<> in the ab

相关标签:
3条回答
  • 2020-12-04 19:47

    Doesn't look right. Now, you might have instead written:

    template<>
    class A<foo> {
    // some stuff
    };
    

    ... which would be a template specialisation for type foo.

    0 讨论(0)
  • 2020-12-04 19:48

    template<> tells the compiler that a template specialization follows, specifically a full specialization. Normally, class A would have to look something like this:

    template<class T>
    class A{
      // general implementation
    };
    
    template<>
    class A<int>{
      // special implementation for ints
    };
    

    Now, whenever A<int> is used, the specialized version is used. You can also use it to specialize functions:

    template<class T>
    void foo(T t){
      // general
    }
    
    template<>
    void foo<int>(int i){
      // for ints
    }
    
    // doesn't actually need the <int>
    // as the specialization can be deduced from the parameter type
    template<>
    void foo(int i){
      // also valid
    }
    

    Normally though, you shouldn't specialize functions, as simple overloads are generally considered superior:

    void foo(int i){
      // better
    }
    

    And now, to make it overkill, the following is a partial specialization:

    template<class T1, class T2>
    class B{
    };
    
    template<class T1>
    class B<T1, int>{
    };
    

    Works the same way as a full specialization, just that the specialized version is used whenever the second template parameter is an int (e.g., B<bool,int>, B<YourType,int>, etc).

    0 讨论(0)
  • 2020-12-04 20:03

    template<> introduces a total specialization of a template. Your example by itself isn't actually valid; you need a more detailed scenario before it becomes useful:

    template <typename T>
    class A
    {
        // body for the general case
    };
    
    template <>
    class A<bool>
    {
        // body that only applies for T = bool
    };
    
    int main()
    {
        // ...
        A<int>  ai; // uses the first class definition
        A<bool> ab; // uses the second class definition
        // ...
    }
    

    It looks strange because it's a special case of a more powerful feature, which is called "partial specialization."

    0 讨论(0)
提交回复
热议问题