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

时间:2012-03-13 17:31:38

标签: c++ templates constructor linker defaults

我有以下模板类,

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)

如果有人能够指出我做错了什么,我会非常感激。

编辑:

好的,我把它缩小到了一些奇怪的东西。

in .h

  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 ;

}

以上述方式出错。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用其他编译器吗?我尝试使用它,以下工作对我来说很好用gcc。我没有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$ 

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

Why do C++ template definitions need to be in the header?

答案 1 :(得分:0)

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