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

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

提前致谢!

最佳答案

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

square<int>(2);

Live Demo

关于c++ - 当 C++ 中也有非模板函数时,调用专门的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176398/

相关文章:

c++ - 求助碰撞方程

c++ - 从内存中绘制位图

templates - 用于静态 Web 开发的简单模板系统

c++ - 将可变参数模板列表中的整数值分配给静态常量 std::array 成员

templates - 在 consul-template 的循环中覆盖变量

c++ - 类模板错误

c++ - 了解 C++ 程序的 GDB 语法

c++ - 两种模板类型和两个模板参数列表有什么区别?

c++ - C++ 中有标准的日期/时间类吗?

c++ - Qt/C++ 将通用对象序列化为 QSettings