C++:我正在做的事情的名称和链接?

C++: Name and linkage of what I'm doing?

本文关键字:链接 C++      更新时间:2023-10-16

寻找此类模板专用化的正式名称和链接类型,其中我们专门化模板只是为了专门实现类模板中的单个方法。

template <class T>
class Foo
{
public:
    void f() 
    {
        // default method implementation
    }
};
// What is the default linkage of this function (I'm guessing 
// external based on basic function template specializations), 
// and what am I doing called? (method specialization of a class 
// template?)
template <> 
void Foo<int>::f()
{
     // method implementation for Foo<int>
}
Foo<int> f1; f1.f(); //Use implementation for Foo<int>, i.e. the specialized one.
Foo<double> f2; f2.f(); //Use the default implementation.

这种情况背后的术语称为显式专业化。编译器将选择它能找到的"最佳"匹配模板。确定"最佳"匹配模板的过程有点复杂。您可以参考"C++模板:完整指南"一书了解更多详情。