gpt4 book ai didi

c++ - 来自单独文件的模板函数的前向声明

转载 作者:行者123 更新时间:2023-12-03 02:40:34 25 4
gpt4 key购买 nike

其他.cpp

#include <iostream>
#include <string>
using std::cout;

template <typename T>
std::ostream & cprint(T &t, std::string msg = "Container", std::ostream & stream = cout){
stream << msg << "\t{ ";
for(typename T::iterator it = t.begin(); it != t.end(); it++)
stream << *it << " ";
stream << "}\n";

return stream;
}

我在单独的文件中有一个模板函数。我正在尝试在 ma​​in.cpp 文件中转发声明它。

extern template std::ostream & cprint<std::vector<int>>
(T &t, std::string msg = "Container", std::ostream & stream = cout);

我已经尝试了上面的方法,但它对我不起作用。

编辑:假设 other.cpp 具有如下基本功能,

template <typename T>
void func(T x){
cout << x << endl;
}

如何在main.cpp中实例化这个函数?

最佳答案

请记住,您所询问的(通常)不是使用模板的正确方法。

您应该做的是在 header 中声明您的模板并删除 extern声明和显式特化。

将模板放入 .cpp通常不是很方便,因为它们要求您在同一个 .cpp 中指定您希望它们工作的所有类型。 .

但是,另一方面,它提高了编译速度,并且生成的二进制文件有可能会更小。

<小时/>

如何修复代码:

我对您的代码进行了一些更改以使其正常工作。

我还做了一些小的改进。如果您发现它们令人困惑,请在评论中询问。

// 1.cpp
#include <iostream>
#include <string>
#include <vector>

template <typename T>
std::ostream &cprint(const T &t, std::string msg = "Container", std::ostream &stream = std::cout)
{
stream << msg << " { ";
for(typename T::const_iterator it = t.cbegin(); it != t.cend(); it++)
stream << *it << " ";
stream << "}\n";
return stream;
}

template std::ostream &cprint(const std::vector<int> &, std::string, std::ostream &);

// 2.cpp
#include <string>
#include <iostream>
#include <vector>

template <typename T> std::ostream &cprint(const T &, std::string = "Container", std::ostream & = std::cout);

int main()
{
std::vector<int> v{1,2,3};
cprint(v);
}

重要部分如下:

  • 显式实例化。它必须与模板定义位于同一文件中。
    template std::ostream &cprint(const std::vector<int> &, std::string, std::ostream &);

  • 声明。它必须位于您要使用模板的文件中。 template <typename T> std::ostream &cprint(const T &, std::string = "Container", std::ostream & = std::cout);

请注意,如果编译器无法推断出模板参数,您可以在显式实例化和外部声明中手动指定模板参数。

<小时/>

用编辑成问题的虚拟模板做同样的事情,留给读者作为练习。

关于c++ - 来自单独文件的模板函数的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667210/

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