【发布时间】:2020-04-27 16:55:42
【问题描述】:
我想推迟(大)一堆类的实例化,其中只有一小部分会被实例化。为此,我尝试在可变参数类中捕获构造函数的参数,并将它们存储在一个元组中。
我的问题是我只成功地存储了引用或副本。但是,我需要同时将这两种类型都转发给构造函数,否则我会遇到范围问题。
#include <iostream>
#include <utility>
#include <tuple>
#include <vector>
// Interface of the classes which instanciation is being deferred.
struct OpItf {
virtual void operator()() = 0;
virtual ~OpItf() {}
};
struct Operator : public OpItf {
int& _i;
int _j;
// Need both a lvalue reference and a rvalue.
Operator(int& i, int j) : _i(i), _j(j) {}
void operator()() {std::cout << _i << " " << _j << std::endl;}
virtual ~OpItf() {}
};
// The interface of the class managing the actual instanciation.
template<class Itf>
struct ForgeItf {
virtual Itf& instanciate() = 0;
virtual ~ForgeItf() {}
};
template<class Itf, class Op, typename... Args>
struct Forge : public ForgeItf<Itf> {
std::tuple<Args&&...> _args;
Itf* _instanciated;
Forge(Args&&... args) :
_args(std::forward<Args>(args)...),
_instanciated(nullptr)
{ }
Itf& instanciate()
{
if(_instanciated) {
delete _instanciated;
}
_instanciated = op_constructor(_args);
return *_instanciated;
}
virtual ~Forge() { delete _instanciated; }
template<class T>
Op* op_constructor(T& args) { return new Op(std::make_from_tuple<Op>(args)); }
};
// A container of forges.
template<class Itf>
struct Foundry : std::vector< ForgeItf<Itf>* > {
template<class Op, typename... Args>
void add(Args&&... args)
{
auto pfo = new Forge<Itf,Op,Args&&...>(std::forward<Args>(args)...);
this->push_back(pfo);
}
virtual ~Foundry() { for(auto p : *this) { delete p; } }
};
int main() {
Foundry<OpItf> foundry;
int iref = 1;
// Store the constructors parameters.
for(int j=0; j<3; ++j) {
foundry.add< Operator >(iref,j);
}
// Change the referenced parameter before instanciations.
iref = 2;
// Actually instanciate.
for(auto& forge : foundry ) {
auto& op = forge->instanciate();
op();
}
}
使用右值Args...,构造函数获取值,但对i 的引用(错误地)没有改变:
1 0
1 1
1 2
使用转发引用Args&&...,构造函数可以正确获取引用,但j 的副本超出范围:
2 1228009304
2 1228009304
2 1228009304
【问题讨论】:
-
我不能replicate这个问题。不过你有一堆警告,所以你应该先解决这个问题。
-
Forge(Args&&... args) : _args(std::forward<Args>(args)...),— 你知道这里的args没有转发引用,因此“转发”它们可能不会像你期望的那样工作吗?
标签: c++ c++17 variadic-templates perfect-forwarding