有没有一种方法可以避免在std :: variant类成员中为所有类型编写构造函数?

时间:2020-01-10 07:28:52

标签: c++ constructor c++17 variant

我有一个struct,例如:

struct A
{
    int a;
    std::variant<int, float, char> b;

    A() = default;
};

我想添加一个构造器,该构造器将同时初始化ab。看来我将不得不为b中的所有类型(例如A::A(int a1, int b1)A::A(int a1, float b1)等)编写一个构造函数。

有办法避免这种情况吗?

2 个答案:

答案 0 :(得分:8)

您可以为您的类创建一个模板化的构造函数,并充其量运用完善的转发将其参数传递给$node = Node::load($cid); if (empty($node)) { return FALSE; } $languages = $node->getTranslationLanguages($include_default = TRUE); foreach($languages as $lang) { $node_translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, $lang); $node_translation->set('field_ship_name', $name); $node_translation = $node_translation->save(); } 成员的构造函数:

function addText(){
  var ss = SpreadsheetApp.getActiveSpreadsheet(); //Getting active spreadsheet
  var s = ss.getActiveSheet();  //Getting active sheet

  var sheetName = s.getSheetName(); //Getting active sheet name
  var lastRow = s.getLastRow(); //Getting sheets last row number

  if (sheetName == "sheetName") { //Checking if active sheet is that we want to be
  var jobValuesRange = s.getRange("C8:C" + lastRow); //Getting range that is only one column
  var jobValues = jobValuesRange.getValues(); //Getting values from only one column

    for (var i = 0; i < jobValues.length + 1; i++) { //Looping through all array values
     if (jobValues[i] == "") { 
       //Here is MAGIC where you must add brackets to create two dimension array.
       //Array should be like with lot of rows like first dimension and second dimension,
       //like one cell in that row. 
       jobValues[i] = [jobValues[i - 1] + " night"]; 
     }
    }
    jobValuesRange.setValues(jobValues); // Here you are just updating old values to new values
  }
}

然后,您可以编写例如:

variant

不会涉及不必要的举动/副本/临时工作。

答案 1 :(得分:2)

我想类似的事情也可以完成,但是,它将复制您传递的变体。

A::A(int a1, std::variant<int, float, char> b1)

仅传递必需类型的能力可能是一个优势。但是,我不建议在其他答案的解决方案上使用它。