C++可变参数模板委派周期错误
C++ variadic template delegation cycle error
我想编写一个帮助程序结构来测试类的静态条件。如果条件为 true,则应在堆中分配一个对象,并且应将指向该对象的指针重新嵌入到 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 结构中的构造函数应该调用其父级的构造函数,但 C++11 还引入了在构造函数中调用构造函数的功能(委托)。所以编译器接缝认为我想在同一类中调用构造函数,导致此错误:
./main.cpp:83:34: error: constructor for 'cond' creates a delegation cycle [-Wdelegating-ctor-cycles]
只需将向量移动到全局范围并删除构造函数参数即可,但我更喜欢其他解决方案。
是否可以告诉编译器以某种方式解释 cond( _b )对吗?
只需通过给出完整的类型来明确您使用类的哪个部分:
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...)
{
}
};
相关文章:
- Pisano 周期生成器在 3 位周期内行为不正确
- 如何在共享库的整个生命周期内存储数据
- 扩展类,委派运算符和分配?
- 提升图形库:资源受限的最短周期
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 如何理解句子的生命周期始于对e的评估
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了
- 找到包括特定边的最短周期
- Go/C++gRPC客户端通道和存根生命周期
- 如何将"this"的生命周期移动到C++中的另一个对象中?
- 是否可以通过使用移动/交换 c++11 来延长返回的临时变量的生命周期
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- C/C++ 经过的流程周期,不包括断点处
- 委派的 ctor 是否受参数计算顺序的影响?
- 标准::计时::时钟、硬件时钟和周期计数
- 使用对象的生命周期作为设置器的安全性
- 委派复制构造函数和常量数据初始化
- time_t的时钟周期和获取时间问题
- 查询时间/周期是针对所有内核/线程的序列化请求还是并行请求?
- C++可变参数模板委派周期错误