[英]Compile time size of data member std::array in non-class template (C++14)
[英]C++14 compile time std::array with variadic templates
我想使用c ++ 14可變參數模板構建編譯時查找表。 目前我在那里:
static const unsigned kCount = 5;
template<unsigned Index>
constexpr auto getRow(void)
{
return std::array<unsigned, 2> { Index, Index * Index };
}
template<unsigned... Indices>
constexpr auto generateTable(std::index_sequence<Indices...>)
{
return std::array<std::array<unsigned, 2>, sizeof...(Indices)>
{
// This is were I'm stuck. How to build a std::array using Indices as template parameter in getRow()?
};
}
constexpr auto generate(void)
{
return generateTable(std::make_index_sequence<kCount>{});
}
我希望表在std::array
。 每行包含一個帶有2列的std::array
。 我陷入了generateTable()
,我需要以某種方式將我的Indices傳遞給getRow()
作為模板參數。
這可以使用std::integer_sequence
和模板參數包擴展來實現,還是我需要自己實現遞歸?
( getRow()
被簡化 - 值類型實際上來自模板類型。 Index * Index
只是一個占位符。我需要知道如何使用參數包擴展調用getRow()
。)
看起來你幾乎就在那里。 只需依靠參數包擴展:
return std::array<std::array<unsigned, 2>, sizeof...(Indices)>
{
getRow<Indices>()...
};
其中getRow<Indices>()...
行將擴展為:
getRow<0>(), getRow<1>(), ..... , getRow<sizeof...(Indices)-1>()
+1為KyleKnoepfel的解決方案,但我在amd64 linux中編譯代碼時出現問題,因為“錯誤:沒有匹配函數來調用'generateTable'”和“候選模板被忽略:替換失敗:推斷出的非類型模板參數沒有與其對應的模板參數相同的類型('unsigned long'vs' unsigned int')“
問題是std::make_index_sequence<kCount>{}
生成一系列std::size_t
。 如果將std::size_t
定義為unsigned int
,則一切順利; 如果(在我的平台中) std::size_t
被定義為unsigned long
,則以下聲明不起作用
template<unsigned... Indices>
constexpr auto generateTable(std::index_sequence<Indices...>)
建議:使用std::size_t
而不是unsigned
; 尤其
template<std::size_t ... Indices>
constexpr auto generateTable(std::index_sequence<Indices...>)
En passant,用{ val1, val2 }
(只有一個大括號)初始化一個std::array
它在C ++ 14中是完全合法的但是(恕我直言)我認為最好使用舊的(C ++ 11)語法雙層括號( { { val1, val2 } }
); 這是為了向后兼容(如Wum所指出的)並避免使用某些編譯器(如clang ++ 3.5)發出惱人的警告。 所以我建議在數組聲明/初始化中使用第二級括號,所以
return std::array<unsigned, 2> { { Index, Index * Index } };
和
return std::array<std::array<unsigned, 2>, sizeof...(Indices)>
{ { getRow<Indices>() ... } };
ps:抱歉我的英語不好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.