gpt4 book ai didi

c++ - 将C++模板函数定义存储在.CPP文件中

转载 作者:行者123 更新时间:2023-12-02 10:57:42 24 4
gpt4 key购买 nike

我有一些模板代码,希望将其存储在CPP文件中,而不是内联在 header 中。我知道只要您知道将使用哪种模板类型就可以做到。例如:

.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一起使用,因此这些定义意味着应用程序将链接。

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

最佳答案

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

我建议从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?

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

    关于c++ - 将C++模板函数定义存储在.CPP文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598595/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com