简体   繁体   中英

Function template specialization without templated argument

Let's look on a template function which take void argument and returns void:

template<class T>
void f() {
    cout << "template" << endl;
}

Later we specialize this function:

template<>
void f<int> () {
    cout << "int" << endl;
}
template<>
void f<double> () {
    cout << "double" << endl;
}

int main() {
    f<int> ();
    f<double> ();
}

The question is why this compiles? We have three function with the same signature: void(void) , and I expected that it should broke with multiple declaration?

This is because you are explicitly stating which function to use. f<int>() can not map to f<double>() because of the difference in template argument; ie this is a completely unambiguous call.

Why shouldn't it work? Those are three different implementations, depending on the template parameter. Each different value you use when instantiating a template creates a completely new copy of the entire templated thing. So here you make three functions, they're all unique and it works fine.

By the way, the symbol name won't be just f , look up C++ name mangling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM