Ian
Ian

Reputation: 3709

Template specialisation in C++ with const

I'm obviously misunderstanding something important about template specialization, because:

template<typename type> const type getInfo(int i) { return 0; }
template<> const char* getInfo<char*>(int i) { return nullptr; }

fails to compile with:

src/main.cpp:19:24: error: no function template matches function
        template specialization 'getInfo'

while

template<typename type> type getInfo(int i) { return 0; }
template<> char* getInfo<char*>(int i) { return nullptr; }

works fine. How do I use const with template specializations? What is my rookie mistake?

I am using c++11 on clang++.

Upvotes: 1

Views: 874

Answers (2)

Slava
Slava

Reputation: 44238

If you need to be able to return string constant just use this:

template<typename type> type getInfo(int i) { return 0; }
template<> const char* getInfo<const char*>(int i) { return nullptr; }

What you tried to do is something like:

const int getInfo( int i ) { return 0; }

it does not make much sense.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

Note that, in the first example, the return type is const type, so the const applies to the whole type. If type is char* (as in your specialisation), then the return type is a char * const. This compiles just fine:

template<typename type> const type getInfo(int i) { return 0; }
template<> char* const getInfo<char*>(int i) { return nullptr; }

This makes sense - if specializing the type as a pointer. Why should the template have any say over what the pointer points to?

However, in this situation, I don't see much reason for having the return type be const.

Upvotes: 5

Related Questions