引用我的问题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. 类中该函数的原型(prototype)是什么?
请推荐
最佳答案
和前面完全一样,只是省略了正文:
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
}
关于c++ - 在类内声明模板化函数(通过容器类型)并在模板类之外通过容器类型定义它 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22526402/