簡體   English   中英

C ++向量列表初始化程序無法與我的課程的類型轉換構造函數一起使用

[英]c++ vector list initializer not working with type converting constructor for my class

我創建了一個帶有“類型轉換構造函數”(接受不同類型的單個參數的構造函數)的類。 我無法使用列表初始化語法來創建該類的向量。

將我的課程包裝在Boost Variant中,可以使相同的課程以相似的語法工作。

為了使用列表初始化語法將類添加到向量中,我最少要做什么?

完整程序:

#include <boost/variant.hpp>
#include <iostream>
#include <string>
#include <vector>

using namespace std;
using boost::variant;

struct S {
  string s;
  S() {}
  ~S() {}
  S(const string& _s) : s(_s) {
    // Type converting constructor.
  }
};

int main() {
  // This works.
  S x{"abcd"};
  cout << "x: " << x.s << endl;

  // Why does this not compile?
  // I'm trying to create a vector with a single element in it.
  vector<S> vs{"vec_abcd"};

  // This works.
  vector<boost::variant<string>> vnts{"vnt_abcd0"};
  cout << "vec: " << boost::get<string>(vnts[0]) << endl;
}

您需要另一組花括號才能使用std::initializer_list構造函數。

vector<S> vs{"vec_abcd"};

嘗試使用const char[]參數構造向量,該參數將不起作用

vector<S> vs{{"vec_abcd"}};

另一方面,使用單個元素初始化程序列表初始化向量。 看起來像

vector<S> vs{{"vec_abcd"}};
            |^list data ^|
            ^ ctor call  ^

現場例子

另外,如果您想限制向量中的多個S ,則可以使用

vector<S> vs{{"a"}, {"b"}, {"c"}, ..., {"z"}};

每個逗號分隔的內部花括號都對應於向量中所需的每個S

您正在嘗試初始化向量,該向量具有類型為const char *且根據C ++標准(SC22-N-4411.pdf)標題為“轉換”的12.3.4節的構造函數S(const string& _s)

4最多將一個用戶定義的轉換(構造函數或轉換函數)隱式應用於單個值。

所以...

  1. 將const char *轉換/ vector<S> vs{ std::string("vec_abcd") }為std :: string vector<S> vs{ std::string("vec_abcd") }
  2. 初始化std::string然后初始化向量。 vector<S> vs{ {"vec_abcd"} }兩個級別的初始化將需要兩個級別的間接vector<S> vs{ {"vec_abcd"} }以及兩個級別的嵌套括號初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM