在C ++中,如何制作一个可以包含相同变体向量的变体? [英] In C++, how to make a variant that can contain a vector of of same variant?

查看:90
本文介绍了在C ++中,如何制作一个可以包含相同变体向量的变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个std :: variant,它可以包含相同变体的向量:

  class ScriptParameter; 
使用ScriptParameter = std :: variant< bool,int,double,std :: string,std :: vector< ScriptParameter> > ;;

我正在重新定义ScriptParameter。



有没有办法实现也可以包含相同类型变量的数组的变量?



p>

解决方案

由于前向声明说 ScriptParameter 是一个类,因此您不能使用使用别名。但是,这里并没有什么内在的错误,因为 vector 只是一个指针,所以没有真正的循环依赖。



您可以使用继承:

  class ScriptParameter; 
类ScriptParameter
:公共std :: variant< bool,int,double,std :: string,std :: vector< ScriptParameter> >
{
public:
使用base = std :: variant< bool,int,double,std :: string,std :: vector< ScriptParameter> > ;;
使用base :: base;
使用base :: operator =;
};

int main(){
ScriptParameter sp { hello};
sp = 1.0;
std :: vector< ScriptParameter> vec;
sp = vec;
std :: cout<< sp.index()<< \n;
}


I a trying to make a std::variant that can contain a vector of the same variant:

class ScriptParameter;
using ScriptParameter = std::variant<bool, int, double, std::string, std::vector<ScriptParameter> >;

I am getting ScriptParameter redefinition. It think it is possibly because a template parameter cannot be forward declared?

Is there a way to achieve a variant that could also contain an array of same typed variants?

解决方案

Since the forward declaration says ScriptParameter is a class, you can't use using alias. However, nothing is inherently wrong here, since vector is only a pointer, there is no real circular dependency.

You can use inheritance:

class ScriptParameter;
class ScriptParameter
    : public std::variant<bool, int, double, std::string, std::vector<ScriptParameter> >
{
public:
    using base = std::variant<bool, int, double, std::string, std::vector<ScriptParameter> >;
    using base::base;
    using base::operator=;
};

int main() {    
    ScriptParameter sp{"hello"};
    sp = 1.0;
    std::vector<ScriptParameter> vec;
    sp = vec;    
    std::cout << sp.index() << "\n";  
}

这篇关于在C ++中,如何制作一个可以包含相同变体向量的变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆