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

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

问题描述

我有一些模板代码,我宁愿存储在一个CPP文件,而不是inline在标题。我知道这可以做,只要你知道将使用哪些模板类型。例如:

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: :字符串,所以这些定义意味着应用程序将链接。

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.

推荐答案

可以通过在标题中定义模板或通过上面介绍的方法来解决。我建议您从 C ++常见问题解答Lite 中阅读以下几点:

The problem you describe can be solved by defining the template in the header, or via the approach you describe above. I recommend reading the following points from the C++ FAQ Lite:

  • Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
  • How can I avoid linker errors with my template functions?
  • How does the C++ keyword export help with template linker errors?

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

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

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

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