0

What is the difference between the following reference to a templated object in C++?

template<typename T>
void myFunction(Object<T>& const obj);

template<typename T>
void myFunction(const Object<T>& obj);

template<typename T>
void myFunction(Object<T> const & obj);
afp_2008
  • 1,940
  • 1
  • 19
  • 46
  • 2
    [This question](https://stackoverflow.com/questions/3694630/c-const-reference-before-vs-after-type-specifier) covers your second and third ones. The "templated" part is irrelevant. The `Object& const` form is actually [quite misleading](https://isocpp.org/wiki/faq/const-correctness#const-ref-nonsense) because it's equivalent to `Object&` and not either of the apparent equivalents. – Nathan Pierson Sep 08 '22 at 06:12
  • 1
    Although in practice [gcc refuses to compile](https://godbolt.org/z/dq985PxW9) a function with a parameter of type `int& const`, so that might just be entirely invalid syntax rather than a counterintuitive synonym for `int&`. Not sure of the standard language that would be definitive here. – Nathan Pierson Sep 08 '22 at 06:18
  • 1
    Related (pointers instead of references): [What is the difference between `const int*`, `const int * const`, and `int const *`?](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) – JaMiT Sep 08 '22 at 06:23
  • 1
    A question to cover your first case: [Why no const reference in C++ just like const pointer?](https://stackoverflow.com/questions/59639756/why-no-const-reference-in-c-just-like-const-pointer) – JaMiT Sep 08 '22 at 06:30

1 Answers1

4
  • Object<T>& const obj - is a const reference to non-const Object<T> (which doesn't make sense, because a reference cannot be rebound, it's always "constant");
  • const Object<T>& obj - a reference to constant Object<T>;
  • Object<T> const& obj - a reference to constant Object<T>, i.e. same as above (the const keyword applies to the right only if it cannot find anything to the left);
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49