加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 根据c-tor的特定条件选择要初始化的变量?

发布时间:2020-12-16 10:11:15 所属栏目:百科 来源:网络整理
导读:就像我有这个结构: struct S{ S(const S arg) : (arg.bIsDouble ? v1{arg.v1} : v{arg.v}) {} bool bIsDouble{false}; union { vectorint v; double v1; };} ; 如何根据某些条件使复制构造函数初始化’v’或’v1’? 解决方法 我只是将你的工作外包给 Boost
就像我有这个结构:

struct S
{
   S(const S &arg) : (arg.bIsDouble ? v1{arg.v1} : v{arg.v}) {}

   bool bIsDouble{false};   

   union {
      vector<int> v;

      double v1;
   };
} ;

如何根据某些条件使复制构造函数初始化’v’或’v1’?

解决方法

我只是将你的工作外包给 Boost.Variant:

struct S {
    S(const S&) = default;
    boost::variant<double,std::vector<int> > v;
};

如果你不想使用Boost,你可以阅读有关如何编写一个有区别的联合here,然后实现自己的.

因为你只需要两种类型,这不是太复杂,虽然它仍然非常容易出错并涉及很多代码:

struct DoubleOrVector {
    bool is_double;
    static constexpr std::size_t alignment_value = std::max(alignof(double),alignof(std::vector));

    alignas(alignment_value) char storage[std::max(sizeof(double),sizeof(std::vector))];

    DoubleOrVector(double v)
        : is_double(true)
    {
        new (storage) double(v);
    }

    // similar for vector

    DoubleOrVector(const DoubleOrVector& dov) 
        : is_double(dov.is_double)
    {
        if (is_double) {
            new (storage) double(dov.asDouble());
        }
        else {
            new (storage) std::vector<int>(dov.asVector());
        }
    }

    double& asDouble() { 
        assert(is_double);
        return *reinterpret_cast<double*>(storage);
    }

    std::vector<int>& asVector() { 
        assert(!is_double);
        return *reinterpret_cast<std::vector<int>*>(storage);
    }

    // plus other functions here
    // remember to explicitly call ~vector() when we need to
};

然后我们仍然默认我们的副本:

struct S {
    S(const S&) = default;
    DoubleOrVector v;
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读