gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:45 24 4
gpt4 key购买 nike

在这个例子中,怎么可能调用第二个函数呢?

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com