C++ - template instantiation with reference type

前端 未结 2 874
猫巷女王i
猫巷女王i 2021-02-04 08:06

I\'ve heard a little bit about reference-to-reference problem and this resolution. I\'m not very good with C++ Committee terminology, but I understand the \"Moved to DR\" annota

2条回答
  •  孤独总比滥情好
    2021-02-04 09:01

    Interestingly, when I compile your code (Visual C++ 10 Express) I get errors, but also when I try this simpler case:

    int main(int argc, char* argv[]) 
    {
      C x;        // OK
      C x1; // error C2535: 'void C::f(T &)' : member function 
                       // already defined or declared
      return 0;
    }
    

    Seems like the ref-to-ref collapsing defined in the DR you mentioned means that const ref becomes a simple non-const ref within the template. My problem with this is that I don't understand why the second f is not just ignored.

    If I change C so that the second f is const-qualified, this now compiles:

    template 
    struct C {
      void f(T&) { }
      void f(const T& t) const {}
    };
    

    The implication seems to be that when C is instantiated with const anything (ref or not), the two C::f overloads are simply identical, and result in compile-time duplicate detection.

    Perhaps somebody smarter than me can decipher the chain more definitively here.

    EDIT: On reflection, it's not surprising here that T = const int& results in the f overloads being identically instantiated as

    void f(const int&) {}
    

    That's what the compiler is telling me:

    #include "stdafx.h"
    
    template 
    struct C {
      void f(T&) { }
      void f(const T&) { }
    };
    
    int main() {
      C z; // compile error: f cannot be overloaded
      return 0;
    }
    

    gives this error:

    1>test.cpp(6): error C2535: 'void C::f(T)' : member function already 
        defined or declared
    1>          with
    1>          [
    1>              T=const int &
    1>          ]
    1>          test.cpp(5) : see declaration of 'C::f'
    1>          with
    1>          [
    1>              T=const int &
    1>          ]
    1>          test.cpp(10) : see reference to class template instantiation 
                    'C' being compiled
    1>          with
    1>          [
    1>              T=const int &
    1>          ]
    

    I'm not even convinced this has anything to do with the DR.

提交回复
热议问题