Template Specializations vs. function overloading
As convention, I prefer to pass the object as const reference below.
void foo(const A& a)
In most of cases, normal conversions are applied to the arguments when the client invokes the function. For example.
A a;
c.foo(a);
Object a will convert to const reference of class A.
However, when we use template specializations, conversions are not applied to argument types. In a call to specialized version of a template, the argument types in the call must match the specialized version function parameter type(s) exactly. If they don't, then the complier will instantiate an instantiation for the argument(s) from the template definition.
class A
{
};
class C
{
public:
template<typename T>
void foo(T t)
{
printf("void foo(T t)\n");
}
template<>
void foo(const int i)
{
printf("void foo(int i)\n");
}
template<>
void foo(const A& a)
{
printf("void foo(const A a)\n");
}
};
TEST(TemplateTest, TemplateSpecializationTest)
{
C c;
int i = 2;
c.foo(i);
A a;
c.foo(a);
}
Because the parameter to call foo is (A a) install of (const A& a), the complier pick the template version void foo(T t) instead of specialized version void foo(const A& a) .
So, in such case, I prefer to use function overloading instead of template specializations.
class A
{
};
class C
{
public:
template<typename T>
void foo(T t)
{
printf("void foo(T t)\n");
}
template<>
void foo(const int i)
{
printf("void foo(const int i)\n");
}
void foo(const A& a)
{
printf("void foo(const A a)\n");
}
};
TEST(TemplateTest, TemplateSpecializationTest)
{
C c;
int i = 2;
c.foo(i);
A a;
c.foo(a);
}

Works as I expect. Conversions are applied to argument when calls foo() function.
refer to C++ Primer.
Update
If we use template specializations and overloaded functions at the same time. The VC++(VS2005) complier will pick up the overloaded function.
class A
{
};
class C
{
public:
template<typename T>
void foo(T t)
{
printf("void foo(T t)\n");
}
template<>
void foo(const int i)
{
printf("void foo(int i)\n");
}
template<>
void foo(A a)
{
printf("template<> void foo(A a)\n");
}
void foo(A a);
};
TEST(TemplateTest, TemplateSpecializationTest)
{
C c;
int i = 2;
c.foo(i);
A a;
c.foo(a);
}
void C::foo(A a)
{
printf("void foo(A a)\n");
}

But I don’t recommend to use both function templates and nontemplate functions at the same time. Because it will surprise the users to use it.
出处:http://procoder.cnblogs.com
本作品由Jake Lin创作,采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。 任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问或者授权方面的协商,请给我留言。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架