如何编译位于C ++中不同文件中的模板? [英] How to compile Templates located in different files in C++?

查看:135
本文介绍了如何编译位于C ++中不同文件中的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我把所有的源放在一个文件中,程序成功构建。但是当我把它们分成头文件,我得到一个链接错误。



我的程序的主要:
//C++_Class_Templates.cpp

  #include< iostream> 
#include< vector>
#includeQueue.h

using namespace std;

//用于C ++类模板
void main()
{
MyQueue< int> q;
q.Add(1);
q.Add(2);
}

Queue.h看起来像这样

  #pragma once 
#include< vector>

template< typename T>
class MyQueue
{
std :: vector< T>数据;
public:
void Add(T const&);
void Remove();
void Print();

};

,Queue.cpp如下所示:

  #includeQueue.h

template< typename T> void MyQueue< T> :: Add(T const& d)
{
data.push_back(d);
}



当我尝试建立它,我得到这个错误:

  1> main.obj:error LNK2019:未解析的外部符号public:void __thiscall 
MyQueue< int&在函数_main
中引用的所有参数(例如,const&)(?Add @?$ MyQueue @ H @@ QAEXABH @ Z)




更长的答案是:好吧,基本上是与简短的答案相同。有关详细信息,请参阅C ++常见问题解答Lite条目为什么我无法将我的模板类从它的声明,并把它放在一个.cpp文件?除了某些有限的使用场景(比如当你有一小部分已知的参数,你将使用模板,你可以显式实例化它与那些类型),模板的定义必须可用,当您尝试使用它。


When I put all the source in one file, the program successfully builds. However when I split them into header files, I get a link error.

The main of my program: //C++_Class_Templates.cpp

#include <iostream>
#include <vector>
#include "Queue.h"

using namespace std;

//Usage for C++ class templates
void main()
{
     MyQueue<int> q;
     q.Add(1);
     q.Add(2);
}

The Queue.h looks like this

#pragma once
#include <vector>

template <typename T>
class MyQueue
{
     std::vector<T> data; 
   public:
     void Add(T const &);
     void Remove();
     void Print();

};

and the Queue.cpp looks like this:

#include "Queue.h"

template <typename T> void MyQueue<T> ::Add(T const &d)
{
     data.push_back(d);
}

When I try to build it, I get this error:

 1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall
 MyQueue<int>::Add(int const &)" (?Add@?$MyQueue@H@@QAEXABH@Z) referenced in function _main

解决方案

The short answer is: "you don't."

The longer answer is: well, it's basically the same as the short answer. For more information, see the C++ FAQ Lite entry "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?" Except for certain limited-use scenarios (like when you have a small set of known arguments with which you will use the template and you can explicitly instantiate it with those types), the definition of the template must be available when you try to use it.

这篇关于如何编译位于C ++中不同文件中的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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