在模板化类的复制构造函数中使用默认值时出错

Error with using defaults in copy constructor of a templated class

本文关键字:默认值 出错 构造函数 复制      更新时间:2023-10-16

我有以下模板类,

template <typename Real>
class Marker {
 typedef Wm5::Vector3<Real> Position ;
 typedef Wm5::Vector3<Real> Normal ;
 typedef Wm5::Vector3<Real> Color ;
 public:
  Marker(int id = -1, Position position = Wm5::Vector3<Real>::ZERO, Normal normal = Wm5::Vector3<Real>::ZERO, Color color = Wm5::Vector3<Real>::ZERO)
: id_(id), position_(position), normal_(normal), color_(color), cluster_(-1) {}
  ~Marker() {}
 private:
  int id_ ;
  Position position_ ;
  Normal normal_ ; 
  Color color_ ;
  int cluster_ ;
};

template <typename T> 
class MarkerSet {
    typedef Marker<T> MarkerT ;      
    typedef std::vector<MarkerT> MarkerVector ;
public:
    MarkerSet::MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) 
   {id_ = id; markers_ = markers;}      
   MarkerSet::~MarkerSet() {}
private:
    int id_ ;   
    MarkerVector markers_ ;
} ;

当我尝试通过创建MarkerSet对象时

MarkerSet<double> markerSet ; 

获取此链接器错误,

error LNK2001: unresolved external symbol "public: __thiscall     MarkerSet<double>::MarkerSet<double>(int,class std::vector<class Marker<double>,class std::allocator<class Marker<double> > >)" (??0?$MarkerSet@N@@QAE@HV?$vector@V?$Marker@N@@V?$allocator@V?$Marker@N@@@std@@@std@@@Z)

如果有人能给我一个正确的方向,告诉我我做错了什么,我将不胜感激。

编辑:

好吧,我已经把它缩小到一些相当奇怪的事情。

英寸小时

  MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) 
{id_ = id; markers_ = markers;}    

构建精细

而不是在.h

 MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) ;

in.cpp

 template <typename T>
 MarkerSet<T>::MarkerSet(int id, MarkerVector markers) {
  id_ = id ;
  markers_ = markers ;
}

以上述方式出现错误。

有什么想法吗?

你能尝试使用不同的编译器吗?我试着用它玩,下面的对我来说很好。我淘汰了Wm5成员,因为我没有这些成员。粘贴标头和cpp:

test.h

#include <vector>
template <typename Real>
class Marker {
 public:
  Marker(int id = -1,int _position=1)
    : id_(id), position(_position){}
  ~Marker() {}
 private:
  int id_ ;
  int position ;
  Real r;
};

template <typename T> 
class MarkerSet {
    typedef Marker<T> MarkerT ;      
    typedef std::vector<MarkerT> MarkerVector ;
public:
    MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) 
      {id_ = id; markers_ = markers;std::cout<<"Called"<<std::endl;}      
   ~MarkerSet() {}
private:
    int id_ ;   
    MarkerVector markers_ ;
} ;

test.cpp

#include <iostream>
#include <vector>
#include "test.h"
using namespace std;

int main(int argc, const char **argv) {
  cout<<"Hello"<<endl;
  MarkerSet<double> ms;
  return -1;
}

cmd:

bash$ ./test
Hello
Called
bash$ 

模板类定义需要在标题中:

为什么C++模板定义需要在标题中?

可能是因为您没有#include实际的构造函数主体,所以链接器不会为MarkerSet<double>::MarkerSet<double>(int,class std::vector<class Marker<double>,class std::allocator<class Marker<double> > >)"生成所需的代码吗?