调用专门的模板函数,当 C++ 中也有非模板函数时

use*_*039 5 c++ templates

在这个例子中,如何调用第二个函数?

template<class T>
T square(T a) {
    std::cout << "using generic version to square " << a << std::endl;
    return a*a;
}

/// "int" is so special -- provide a specialized function template
template<>
int square(int a) {
    std::cout << "using specialized generic version to square " << a << std::endl;
    return a*a;
}

/// and there's one more: a non-template square function for int
int square(int a) {
    std::cout << "using explicit version to square " << a << std::endl;
    return a*a;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

101*_*010 4

通过显式指定模板参数来调用特化:

square<int>(2);
Run Code Online (Sandbox Code Playgroud)

现场演示