当C ++中还存在非模板函数时,调用专用模板函数

时间:2016-03-23 11:03:53

标签: 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;
}

提前致谢!

1 个答案:

答案 0 :(得分:3)

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

square<int>(2);

Live Demo