C++可变参数模板委派周期错误

C++ variadic template delegation cycle error

本文关键字:委派 周期 错误 变参 参数 C++      更新时间:2023-10-16

我想编写一个帮助程序结构来测试类的静态条件。如果条件为 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...)
    {
    }
};