Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template specialization type - is it optional?

Tags:

c++

templates

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);
}
like image 560
mike Avatar asked Sep 02 '26 14:09

mike


1 Answers

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) {
    // ...
}
like image 141
πάντα ῥεῖ Avatar answered Sep 05 '26 14:09

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!