跨源文件模板实例化和使用

发布于 2024-09-17 06:25:41 字数 160 浏览 2 评论 0原文

我有一个包含多个模板成员函数的类,我想将它们分发到多个源文件中以加快编译时间。 (模板是实现细节,不打算在类外部使用,因此它们的定义在源中而不是标头中。)

我将如何以不会出现链接器错误的方式拆分这些模板?如果我的源文件 A 使用源文件 B 中定义的模板,如何确保编译器构造了模板的适当实例?

I have a class with several template member functions that I would like to distribute among several source files to speed up compilation times. (The templates are implementation details and are not intended to be used outside the class, hence their definition in sources not headers.)

How would I go about splitting up these templates in such a way that I will not get linker errors? If I have source file A using a template defined in source file B, how do I make sure the appropriate instance of the template is constructed by the compiler?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

英雄似剑 2024-09-24 06:25:41

我无法回答比 C++ FAQ 更好的问题:
https://isocpp.org/wiki/faq/templates#templates- defn 与 decl

I could not answer it better than C++ FAQ:
https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl

眼泪也成诗 2024-09-24 06:25:41

只是不要将这些模板项声明为头文件中类的一部分。然后,仅在源文件中定义模板。例如:

MyClass.hpp

class MyClass
{
public:
    void SomePublicMethod() const;
};

MyClass.cpp

template<class T>
void SomethingWithT(T myVal)
{
    // ...
}

void MyClass::SomePublicMethod() const
{
    SomethingWithT(42);
}

Simply don't declare those template items as part of the class in the header file. Then, define your templates only in the source file. For example:

MyClass.hpp

class MyClass
{
public:
    void SomePublicMethod() const;
};

MyClass.cpp

template<class T>
void SomethingWithT(T myVal)
{
    // ...
}

void MyClass::SomePublicMethod() const
{
    SomethingWithT(42);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文