1

Given a template and a more specialized overload:

template <typename T>
const T& some_func(const T& a, const T& b) 
{
    std::cout << "Called base template\n";
    return (a < b) ? a : b; 
}

template <typename T>
T* const& some_func(T* const& a, T* const& b) 
{
    std::cout << "Called T* overload\n";
    return (*a < *b) ? a : b; 
}

Then the following works as expected:

int main()
{
    std::cout << some_func(5.3, 6.2) << "\n";
    double a = 1;
    double b = 2;
    double *p = &a;
    double *q = &b;
    const double *ret = some_func(p, q); 
    std::cout << *ret << "\n";
    return 0;
} 

With the first printing Called base template, the second printing Called T* overload. If we replace the overload signature with:

template <typename T>
const T*& some_func(const T*& a, const T*& b)

then the second call now calls the base template. Given that int const& x is equivalent to const int& x, am I incorrect in assuming T* const& is equivalent to const T*&? Why is the first version resolved properly while the second is not?

3
  • 3
    It's not a specialization here. Commented Aug 3, 2012 at 7:12
  • 1
    @Yuushi - We are marking words here, but you have two overloaded functions, where the second one is more specialized that the first. However, it is not a template specialization, it is two separate function templates. :-) Commented Aug 3, 2012 at 7:23
  • @Flexo Also true. I'll edit the question to reflect that... Commented Aug 3, 2012 at 7:29

2 Answers 2

5

Yes you are incorrect. In const T*& T is const, in T* const& the pointer (T*) is const.

The change happens when you shift const to the right of *. const T*& and T const *& are equivalent but T* const& is different. Typedefs can help, given

typedef T *TPtr;

const TPtr& is equivalent to TPtr const & is equivalent to T* const &.

Declarators in C/C++ are hard to parse (for a human). Even the inventor of C said so.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I guess it should be somewhat obvious when I think about it, but I guess there's no better way to burn it into my brain than asking a silly question...
2

T const & and const T & are identical; and U const * and const U * are identical.

But S & and T const & are not the same even for T = S. What you have is even worse, namely S = U const * and T = U *.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.