Is there any difference between “T” and “const T” in template parameter?

后端 未结 3 830
借酒劲吻你
借酒劲吻你 2020-12-03 20:56

Is there any difference between following 2 syntax:

template struct A;         // (1)

and

template

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

    No.

    §14.1 [temp.param] p5

    [...] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.

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

    I found this doing a quick search of the standard:

    template<const short cs> class B { };
    template<short s> void g(B<s>);
    void k2() {
        B<1> b;
        g(b); // OK: cv-qualifiers are ignored on template parameter types
    }
    

    The comment says they are ignored.

    I'll recommend not using const in template parameters as it's unnecessary. Note that it's not 'implied' either - they're constant expressions which is different from const.

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

    The choice of int was probably a bad idea, it makes a difference for pointers though:

    class A
    {
    public:
        int Counter;
    };
    
    A a;
    
    
    template <A* a>
    struct Coin
    {
        static void DoStuff()
        {
            ++a->Counter; // won't compile if using const A* !!
        }
    };
    
    Coin<&a>::DoStuff();
    cout << a.Counter << endl;
    
    0 讨论(0)
提交回复
热议问题