mike mike - 3 months ago 20
C++ Question

Function template specialization type - is it optional?

Is the

<const char*>
optional in below code? I found that g++ and clang compiles without it just fine.

template<typename T>
void debugRep2(T const& t) {
std::cout << "debugRep(const T& t)\n";
}

template<>
void debugRep2<const char*>(const char* const& t) {
//^^^^^^^^^^^^^
std::cout << "const char*& t\n";
}

int main() {
int n;
int *pn = &n;
debugRep2(n);
debugRep2(pn);
}

Answer

The templated type is already specified at the function parameter and can be deduced by the compiler

template<>
void debugRep2<const char*>(const char* const& t) {
                         // ^^^^^^^^^^^ already present
    // ...
}

So yes, in this case it is optional.


In fact the common way to write that specialization would be

template<>
void debugRep2(const char* const& t) {
    // ...
}
Comments