你能为const成员编写一个联合的拷贝构造函数吗?

Dan*_*ury 6 c++ unions

假设我有一个包含const成员联合的结构,如下所示:

struct S
{
  // Members

  const enum { NUM, STR } type;

  union
  {
    const int a;
    const std::string s;
  };

  // Constructors

  S(int t_a) : type(NUM), a(t_a);

  S(const std::string & t_s) : type(STR), s(t_s);

};
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.但现在说我想为这种类型编写一个复制构造函数.

它似乎不涉及做任何邪恶的事情,但由于我需要在成员初始化器中初始化const成员,我不会看到如何基于依赖于type成员的逻辑来执行此操作.

问题:

  • 是否可以编写此构造函数?

  • 如果不是,这本质上是一种语法上的疏忽,还是有一些根本原因导致语言无法支持这样的事情?

Fed*_*dor 2

是的,这里可以写复制构造函数。实际上它已经在std::variant实现内部完成了,它应该支持const-types 等。所以你的课程S可以替换为

using S = std::variant<const int, const std::string>;
Run Code Online (Sandbox Code Playgroud)

但是,如果由于圆顶原因您无法使用,std::variant则可以使用函数编写复制构造std::construct_at函数,如下所示:

#include <string>

struct S {
  const enum { NUM, STR } type;

  union {
    const int a;
    const std::string s;
  };

  S(int t_a) : type(NUM), a(t_a) {}
  S(const std::string & t_s) : type(STR), s(t_s) {}
  S(const S & rhs) : type(rhs.type) {
      if ( type == NUM ) std::construct_at( &a, rhs.a );
      if ( type == STR ) std::construct_at( &s, rhs.s );
  }
  ~S() {
      if ( type == STR ) s.~basic_string();
  }
};

int main() {
    S s(1);
    S u = s;

    S v("abc");
    S w = v;
}
Run Code Online (Sandbox Code Playgroud)

演示: https: //gcc.godbolt.org/z/TPe8onhWs