const references in c++ templates

后端 未结 3 1314
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 09:53

In a C++ template with the generic type T, I can use

const T &

to get a reference to a constant T. However, if now T itself is a reference

3条回答
  •  忘掉有多难
    2021-02-05 10:22

    You can always use template specialisation to implement a different version for any kind of reference:

    template  struct X {
      void foo(T const&);
    };
    
    template  struct X {
      void foo(T const&);
    };
    

    Now, X::foo expects an int const& and X::foo expects an int const&, too.

    However, it is not entirely clear from your question what you are trying to do exactly.


    Edit: My g++ version (4.6.1) does not complain without template specialisation for the following

    int i = 7;
    X(i);
    

    While it does for

    X(7);
    

    Which is correct IMO, because you try to convert a temporary (7) to a mutable reference (even if that is a reference to a const reference).


    Edit 2: If you want to reduce duplicate code, then do not specialise your original class, but use this:

    template  struct R {
      typedef T& Ref;
      typedef T const& ConstRef;
    };
    
    template  struct R {
      typedef T& Ref;
      typedef T const& ConstRef;
    };
    
    template struct X {
      void foo(typename R::ConstRef x);
    };
    

提交回复
热议问题