将 C++ 模板函数定义存储在 .CPP 文件中 [英] Storing C++ template function definitions in a .CPP file

查看:50
本文介绍了将 C++ 模板函数定义存储在 .CPP 文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些模板代码,我希望将它们存储在 CPP 文件中,而不是内嵌在标题中.我知道只要您知道将使用哪些模板类型,就可以做到这一点.例如:

I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:

.h 文件

class foo
{
public:
    template <typename T>
    void do(const T& t);
};

.cpp 文件

template <typename T>
void foo::do(const T& t)
{
    // Do something with t
}

template void foo::do<int>(const int&);
template void foo::do<std::string>(const std::string&);

请注意最后两行 - foo::do 模板函数仅用于 ints 和 std::strings,因此这些定义意味着应用程序将链接.

Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.

我的问题是 - 这是一个讨厌的黑客还是可以与其他编译器/链接器一起使用?我目前仅在 VS2008 中使用此代码,但希望移植到其他环境.

My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.

推荐答案

您描述的问题可以通过在标题中定义模板或通过您上面描述的方法来解决.

The problem you describe can be solved by defining the template in the header, or via the approach you describe above.

我建议阅读 C++ FAQ Lite 中的以下几点:

I recommend reading the following points from the C++ FAQ Lite:

他们详细介绍了这些(和其他)模板问题.

They go into a lot of detail about these (and other) template issues.

这篇关于将 C++ 模板函数定义存储在 .CPP 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆