在类内部模板化函数的声明(在容器类型上),并在容器类型上的模板类之外定义它 -

时间:2014-03-20 07:38:51

标签: c++ templates c++11

参考我的问题here

我有一个模板类,如下所示:

//traits.hpp
 namespace traits {
  typedef std::vector <int>  container_t;
  typedef std::set <int>    container_t2;
  typedef std::list <int>    container_t3;

};

//FOO.hpp
class FOO { 
  public:
    static int a; static int b; static int c; 
 };
 int FOO::a = 10;  int FOO::b = 20;  int FOO::c = 30;


// BAR.hpp
using namespace traits;

template <class FOO>
class BAR {
  public:
   BAR : m_a (FOO::a), m_b (FOO::b), m_c (FOO::c)  {  } 


  // I can happily do this. ===>> VALID
  template <template <typename, typename> class ContainerT, typename ValueT>
  void Initialize(ContainerT <ValueT, std::allocator <ValueT>>&  container) 
  {
    typedef ContainerT<ValueT, std::allocator <ValueT>> type;
    int id = 0;
    for (auto& i : container)
       i = id++;
  }


  void DO_THIS () 
  { 
     Initialize (my_container)
  }

 private:
  container_t  my_container;
   int m_a, m_b, m_c;
}

 // in main.
  BAR <FOO> bar_object;
  bar_object.DO_THIS ();    // calls the initialize function. which is fine.

我只想这样做:在类外定义Initialize模板函数。

using namespace traits;

template <class FOO>
class BAR {
  public:
   BAR : m_a (FOO::a), m_b (FOO::b), m_c (FOO::c)  {  } 

  // prototype of Initialize 
  void Initialize ( **?? what to put here ??** ); 
  // I cant put container_t&  BECAUSE  I have several containers such as  
  // set/vector/list. 
  // If I want to initialize the container using set / vector / list, the prototype
  // will be incorrect.
  // i cant declare a prototype for each container type. 

  void DO_THIS () 
  { 
     Initialize (my_container1);
     Initialize (my_container2);
  }

 private:
  container_t1  my_container1;
  container_t2  my_container2
   int m_a, m_b, m_c;
 };


  // unable to define the function properly outside the class. 
  // gives template errors

  template <template <typename, typename> class ContainerT, typename ValueT>
  void Initialize(ContainerT <ValueT, std::allocator <ValueT>>&  container) 
  {
    typedef ContainerT<ValueT, std::allocator <ValueT>> type;
    int id = 0;
    for (auto& i : container)
       i = id++;
  }

我可以在类中编写函数模板Initialize()而不会出现任何错误。但我想把它写在外面。我之前发表的评论很有帮助,但我不得不改变我的实现

简而言之,我想要的是: 1.将泛型函数模板写在类外的容器类型上。 2.该类内部函数的原型是什么?

请建议

1 个答案:

答案 0 :(得分:1)

与以前完全相同,只省略身体:

template <class FOO>
class BAR {
  public:
   BAR : m_a (FOO::a), m_b (FOO::b), m_c (FOO::c)  {  } 

  template <template <typename, typename> class ContainerT, typename ValueT>
  void Initialize(ContainerT <ValueT, std::allocator <ValueT>>&  container);

  // ... rest unchanged
};

// Definition outside:

template <class FOO>  // for the class
template <template <typename, typename> class ContainerT, typename ValueT>  // for the function
void BAR<FOO>::Initialize<ContainerT, ValueT>(ContainerT <ValueT, std::allocator <ValueT>>&  container)
{
  // same as before
}