我有一个关于多态和可能的其他技术的问题。考虑以下方案:
#include <vector>
#include <memory>
using namespace std;
struct Base
{ };
struct Derived : Base
{ };
class group
{
private:
vector< unique_ptr<Base> > V;
public:
group( /* what to put here? */ )
: V( /* again: how to construct V? */ )
{ }
}
这里有三个类:一个基类,叫做Base
; 一个派生类,叫做Derived
; 还有一个最后的类,group
,它将充当一个包装器来保存Base
指针。但我想要实现以下功能:
Use move semantics. There should be no copies involved. The caller should be able to give the constructor several temporaries, as the constructor would steal them:
group my_wonderful_group( Base( /* parameters */ ) , Derived ( /* ... */ ) , Derived ( /* ... */ ) );
Initialize
V
in the initialization list. That way,V
could be const-qualified (despite all the other benefits initializing member objects in initialization lists carries).
#include <string>
#include <vector>
#include <memory>
#include <initializer_list>
#include <iostream>
using namespace std;
struct Base
{
string s;
Base(Base && b) : s(move(b.s)) { }
Base(const string & S) : s( S ) { }
};
struct Derived : Base
{
Derived(const string & S) : Base( S ) { }
};
unique_ptr<Base>
BASE ( const string & S )
{
return unique_ptr<Base>( new Base(S) );
}
unique_ptr<Base>
DERIVED ( const string & S )
{
return unique_ptr<Base>( new Derived(S) );
}
class C
{
private:
vector< unique_ptr<Base> > V;
public:
template<typename ... T>
C
( T ... t ) : V({ t... })
{ }
void
print
( void )
{
for ( const auto & x : this->V )
cout << x->s << endl;
}
;
};
int main(void)
{
C c( BASE("hola") , DERIVED("der1") , DERIVED("bor3") );
c.print();
return 0;
}
然而,它抱怨在
group
构造函数中展开并用逗号分隔放入初始化列表V
的参数包中调用了unique_ptr
的[deleted]复制构造函数。我想我的问题归结为一个
vector
,实际上,这个问题可以应用于一个vector<unique_ptr<Base>>
(/*用派生类初始化*/)。我认为这一定是以前解决过的,因为多态性是基本的C++,保存派生类对象似乎是非常常见的用法。顺便说一下,我使用的是g++ 4.8.1
。提前感谢。最好的祝福, Kalrish
P.S.: 我刚刚阅读了这个问题,它似乎部分涵盖了我的问题。