向量如何存储这些没有相同类的对象?
嗯,确实如此 不 存储此类对象的向量(直接),而不是新创建的对象 boost::function 向量内的对象将存储实例。这个对象怎么会这样做?
boost::function
一些简单的演示类说明了这一点 可以 实施:
// first need a generic template allowing the Demo<void(void)> syntax template <typename S> class Demo; // now specialising (otherwise, we'd need to instantiate Demo<void, void>) template <typename R, typename ... PP> class Demo<R(PP...)> { class Wrapper { public: virtual ~Wrapper() { } virtual R operator()(PP...) = 0; }; template <typename T> class SpecificWrapper : public Wrapper { T t; public: SpecificWrapper(T& t) : t(t) { }; virtual R operator()(PP...pp) { return t(pp...); } }; // the trick: pointer to POLYMORPHIC type! Wrapper* w; public: // be aware that this constructor deliberately is NOT explicit template <typename T> Demo(T& t) : w(new SpecificWrapper<T>(t)) { } R operator()(PP...pp) { return (*w)(pp...); } };
非显式构造函数允许 隐式 创建一个新的Demo对象:
Rcpp::Function r; // simplified just for demo! std::vector<Demo<void(void)>> v; v.push_back(r); // implicit call to non-explicit constructor! equivalent to: v.push_back(Demo<void(void)>(r));
请注意,该类只是最低限度地实现(仅复制构造函数;移动构造函数和适当的赋值运算符可能尚未添加),因为它仅用于演示目的。
我希望能够在运行时内省对象。
您正在寻找 的std ::功能::目标 :
auto l = []() { std::cout << "demo" << std::endl; }; std::function<void(void)> f(l); auto* pl = f.target<decltype(l)>(); if(pl) (*pl)();
但是,这就像需要一样,闻起来有点糟糕的设计 dynamic_cast (哪一个 Demo 最有可能在其自己的变体中使用包装器指针 target )。你为什么要把这个拿回来?难道你不想只是想要处理所有功能,无论是否Rcpp?
dynamic_cast
Demo
target