簡體   English   中英

可變參數模板構造模板列表

[英]Variadic templates construct template list

在下面的代碼中,如何使用列表b來創建object_b,就像使用列表a手動創建object_a一樣?

#include <list>

template <int...Args>
class Object {};

int main() {
    std::list<int> a = {1,2,3,4,5};
    Object<1,2,3,4,5> object_a;
    std::list<int> b;
      // do whatever with b
    // Object< ? > object_b;  // how to use b to create object_b?
}

我最好的解決方案是:

#include <list>

template <std::list<int>& L>
class Object {};

std::list<int> globalList;

int main() {
    std::list<int> a = {1,2,3,4,5};
    globalList = a;
    Object<globalList> object_a;
}

還有更好的主意嗎? 有什么辦法不引入全局變量?

您是否要求能夠使用與std :: list相同的語法來構造對象?

您可以使用std :: initializer_list實現此目的。

class Object{

    Object(const std::initialize_list<int>& vars)
    {
          // do stuff with the vars. 
    }
};

然后你可以做

Object my_object = {1, 2, 3, 4}; 

暫無
暫無

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

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