普通函数重载模板函数但普通不重载模板类?

ordinary function overload template function but ordinary does not overload template class?

本文关键字:重载 函数      更新时间:2023-10-16

为什么允许与函数模板同名的普通函数?但是,不允许使用与类模板同名的普通类。

template<typename T>
class A {};
class A {};    //compilation fails when uncommented
template<typename T>
void func();    //No problem compiling
void func();
int main() {
}

类不能重载,只能重载函数。如果要"重载"类,请使用模板专用化

// The generic class
template<typename T>
class A {};
// Specialization for int
template<>
class A<int> {};
// Specialization for std::string
template<>
class A<std::string> {};
// ...
A<int> my_int_a;  // Uses the A<int> specialization
A<float> my_float_a;  // Uses the generic A<T>