下面的代码可以让我到模板的功能 进行参数是三种不同的指针类型来框对象向量:模板函数来处理阶级和阶级*
const std::vector<std::shared_ptr<Box>>&
const std::vector<std::weak_ptr<Box>>&
const std::vector<Box*>&
是否有办法将其扩展为支持:
const vector<Box>&
const vector<std::reference_wrapper<Box>>
也许是在提升?
#include <vector>
#include <iostream>
class Box{
public:
Box (unsigned int id, unsigned int side): id(id), side(side){}
int volume(){
return side * side * side;
}
unsigned int id;
unsigned int side;
};
template <typename T>
struct is_box_containter {
enum { value = false };
};
template <>
struct is_box_containter <std::vector<std::shared_ptr<Box>>> {
enum { value = true };
};
template <>
struct is_box_containter <std::vector<std::weak_ptr<Box>>> {
enum { value = true };
};
template <>
struct is_box_containter <std::vector<Box*>> {
enum { value = true };
};
template <typename T>
typename std::enable_if<is_box_containter<T>::value>::type
measure(T const& boxes)
{
for (auto& box : boxes) {
std::cout << box->id << " has volume " << box->volume() << std::endl;
}
}
int main(){
std::vector<std::shared_ptr<Box>> some_boxes;
some_boxes.push_back(std::shared_ptr<Box>(new Box(1,4)));
some_boxes.emplace_back(new Box(2, 12));
Box * box_3 = new Box(3, 8);
Box * box_4 = new Box(4, 9);
std::vector<Box*> more_boxes;
more_boxes.emplace_back(box_3);
more_boxes.emplace_back(box_4);
measure(some_boxes);
measure(more_boxes);
return 0;
}
为什么我问这个问题: 我有几乎相同的逻辑,其实现两个功能的应用。一个需要一个SomeClass的列表,另一个需要一个指向SomeClass的向量的向量。 我目前正在计划重构代码来将SomeClass的列表替换为SomeClass的共享指针列表。但我这样做的唯一原因是将逻辑转移到一个通用实现。如果有一个完全合理的方法来避免它,我不想那样做。
您基本上想知道vasriable是否来自'vector&'? –
我不认为这就是我的意思,我想知道是否有一种方法来模板可以处理Class和Class *的函数,来编写将被解释为box-> id或box的代码。身份证号码。看起来像其他人可能会遇到的问题,增强库的编写类型。其实我不知道这是否只是一个问题,我不知道正确的词汇表,所以我没有充分使用Google。 –
你尝试重叠吗? –