我正在尝试创建一个通用容器,它可以存储 Wrapper< T> 类型的异构对象,其中 T 可以是任何用户定义的类型。我见过 boost::any 和其他解决方案,但我不能在不重铸的情况下调用函数 foo()(我不知道要重铸哪种类型,有关 T 的信息丢失。)它回到原始类型。
我如何合理地实现一个通用容器/使用现有的通用容器来实现这一点?
template <typename T>
class Wrapper{
public:
Wrapper(const T& a):o(a){};
Wrapper(){};
//public methods
void foo(){
//do stuff
};
private:
T o;
};
class X{};
class Y{};
int main(){
X x;
Y y;
A_GENERIC_CONTAINER generic_container;
// A_GENERIC_CONTAINER should be able to store
// any number of heterogeneous objects of type Wrapper<T>
// where T can be any user defined type.
generic_container.push_back(x);
generic_container.push_back(y);
auto it = generic_container.begin();
auto end = generic_container.end();
while(it != end){
it->foo();
++it;
}
}
最佳答案
最通用的方法是为 Wrapper 创建一个基类,比如 BaseWrapper,然后在 BaseWrapper 上定义纯虚函数,然后在每个 Wrapper 类上实现这些函数。通过特化,每个 Wrapper,Wrapper,都可以有自己的实现。完成此操作后,您可以使用指向基本类型的智能指针容器,并在闲暇时使用它。
有一些可能的捷径。例如,在您示例中的简单情况下,我建议使用 std::function
。辅助函数有助于执行此操作。请注意,这仅在只有一种方法被调用时才有效。我还建议让您的包装器直接定义 operator()
,这样您就不必使用绑定(bind)。
template<T>
std::function<void()> wrap(const T& x)
{
return std::bind(&Wrapper<T>::foo, Wrapper<T>(x));
}
int main(){
X x;
Y y;
std::vector<std::function<void()> > generic_container;
// A_GENERIC_CONTAINER should be able to store
// any number of heterogeneous objects of type Wrapper<T>
// where T can be any user defined type.
generic_container.push_back(wrap(x));
generic_container.push_back(wrap(y));
auto it = generic_container.begin();
auto end = generic_container.end();
while(it != end){
(*it)();
++it;
}
}
编辑:
我讨论的是非模板化基础,您可以从中派生所有模板化包装器。这允许您调用您预定义的方法(并且必须由包装器实现),而无需知道涉及的特定包装器类型。
class Base
{
public:
virtual ~Base() {};
virtual void foo() = 0;
};
template <typename T>
class Wrapper : public Base{
public:
Wrapper(const T& a):o(a){};
Wrapper(){};
//public methods
virtual void foo(){
//do stuff
};
private:
T o;
};
int main(){
X x;
Y y;
std::vector<std::shared_ptr<Base> > generic_container;
// A_GENERIC_CONTAINER should be able to store
// any number of heterogeneous objects of type Wrapper<T>
// where T can be any user defined type.
generic_container.push_back(std::make_shared<Wrapper<X>>(x));
generic_container.push_back(std::make_shared<Wrapper<Y>>(y));
auto it = generic_container.begin();
auto end = generic_container.end();
while(it != end){
it->foo();
++it;
}
}
关于c++ - 用于在 C++ 中存储特定模板对象的通用容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994416/