我想编写一个辅助结构来测试类的静态条件。如果条件为真,则应在堆中分配一个对象并将指向该对象的指针放回 std::vector。
那些对象看起来像:
class BASE {
public:
virtual void func() = 0;
};
class A : public BASE {
public:
const static int I = 0;
void func() {
std::cout << "CLASS A" << endl;
}
};
class B : public BASE {
public:
const static int I = 1;
void func() {
std::cout << "CLASS B" << endl;
}
};
检查结构:
template<class... R>
struct cond {};
template<class T, class... R>
struct cond<T, R...> : cond<R...> {
cond( vector<BASE *> &_b ) : cond( _b ) {
if( T::I == 1 )
_b.emplace_back( new T() );
}
};
在主函数的某处:
std::vector<BASE *> b;
cond<A, B> t(b);
for( auto *x : b ) {
x->func();
}
理论上cond结构中的构造函数应该调用它parent的构造函数,但是C++11也引入了一个特性,可以在构造函数中调用构造函数(委托(delegate))。所以编译器似乎认为我想在同一个类中调用构造函数,从而导致此错误:
./main.cpp:83:34: error: constructor for 'cond' creates a delegation cycle [-Wdelegating-ctor-cycles]
只需将 vector 移动到全局范围并删除构造函数参数即可,但我更喜欢其他解决方案。
是否可以告诉编译器以某种方式正确解释 cond(_b)?
最佳答案
通过给出complete 类型,明确说明您正在使用类的哪一部分:
template<class... R>
struct cond {};
template<class T, class... R>
struct cond<T, R...> : cond<R...> {
cond( vector<BASE *> &_b ) : cond<R...>( _b ) {
if( T::I == 1 )
_b.emplace_back( new T() );
}
};
:
之后在构造函数中给出完整类型,与类的继承列表中提供的完全相同 - cond<R...>
编辑: 至于没有找到构造函数的错误,请注意它是正确的。这个类:
template<class... R>
struct cond {};
没有,所以你应该添加这样的东西,它应该可以工作:
template<class... R>
struct cond
{
template<typename...T>
cond(T...)
{
}
};
关于C++ 可变参数模板委托(delegate)周期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049356/