首页 > 解决方案 > 普通函数重载模板函数但普通不重载模板类?

问题描述

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

template<typename T>
class A {};

class A {};    //compilation fails when uncommented

template<typename T>
void func();    //No problem compiling

void func();

int main() {

}

标签: c++c++14

解决方案


类不能重载,只能重载函数。如果要“重载”一个类,请使用模板专业化

// 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>

推荐阅读