Avoid angle brackets in default template

后端 未结 3 1003
长情又很酷
长情又很酷 2020-12-16 02:37

If I have a template class with a default template type, I have to write the template angle brackets. Is it somehow possible to avoid this?

Example:

相关标签:
3条回答
  • 2020-12-16 03:05

    Since C++17, because of class template argument deduction, things have changed.

    tt and tt<> are not the same thing: types and class templates were different and continue to be treated differently.

    Anyway in simple scenarios like the one in your example, C++17 assumes what you mean and the <> aren't needed anymore.

    Further details:

    • Template default arguments (specifically https://stackoverflow.com/a/50970942/3235496);
    • Why is <> required when specifying a template class which has defaults for all its template parameters?
    0 讨论(0)
  • 2020-12-16 03:16

    ... if I want to use the class ...

    This is a common source of confusion. A class template is not a class, but a template from which classes are generated. The angle brackets is what tells the compiler that you want to generate a class out of the class template with the given template arguments, without the angle brackets what you have is a template.

    template <typename T = int>
    struct TemplateClass {...};
    
    template <template class T<typename> >
    void f() {
       T<int> t; ...
    }
    template <typename T>
    void g() {
       T t; ...
    }
    
    f<TemplateClass>();     // Accepts a template with a single type argument
    g<TemplateClass<> >();  // Accepts a type, that can be generated out of the template
    

    The language does not allow the coexistence of a template and a type with the same name in the same namespace, so the answer is that it cannot be done. You can create a type alias but you will have to give it a different name.

    0 讨论(0)
  • 2020-12-16 03:21

    You can use typedef...

    typedef tt<> tt_;
    

    And then simply use tt_.

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