2016-11-17 63 views
1

不成功搜索的網頁漫長的一天後的實際的解決方案,以解決我的問題,我決定張貼在這裏我的問題,澄清我的目標,我提供了這個簡單的代碼:獲取每種參數包的大小?

template<typename... types> 
    std::vector<SIZE_T> GetTypesSize() 
    { 
     std::vector<SIZE_T> typesSizeContainer; 
     typesSizeContainer.reserve(sizeof... (types)); 

     /* 
     * What I want here is a mechanism to loop throw 
     * each element of the parameter pack to get its size 
     * then push it into typesSizeContainer. 
     * Something similar to : 
     * For(auto& element : types...) { 
     *  typesSizeContainer.push(sizeof(element)); 
     * } 
     * 
     */ 

     return std::move(typesSizeContainer); 
    } 

當我把這個在此代碼函數模板:

// platform x86 
std::vector<SIZE_T> tempVactor; 
tempVactor = GetTypesSize<char, short, int>(); 

tempVactor的元素應該是{ 1, 2, 4 }

任何建議或解決方案是相當可觀的。

回答

2

我會建議使用std::array爲:

template<typename... Types> 
constexpr auto GetTypesSize() { 
    return std::array<std::size_t, sizeof...(Types)>{sizeof(Types)...}; 
} 
+0

As @ W.F。提到你的答案提供了我正在尋找的實用解決方案,我很感激。 –

+0

在同一行代碼中使用'sizeof'和'sizeof ...'的一個很好的例子。 – Bernard

5

你可以只初始化解包大小的矢量:

template<typename... types> 
std::vector<size_t> GetTypesSize() 
{ 
    return { sizeof(types)... }; 
} 

demo

+0

我感謝您的幫助。 –

+2

@AmraneAbdelkader也考慮將結果類型更改爲數組(它具有編譯時間已知的大小),這將允許該函數得到更好的... –

+0

@ W.F。對,對於你的主張來說,這是一個重要的觀點。 –

1

還有另一種可能的解決方案,它說明了如何使用解決問題SFINAE

template<size_t N> 
typename std::enable_if<N == 0>::type get(std::vector<std::size_t>& sizes) {} 

template<size_t N, typename T, typename... Args> 
typename std::enable_if<N != 0>::type get(std::vector<std::size_t>& sizes) { 
    sizes.push_back(sizeof(T)); 
    get<N - 1, Args...>(sizes); 
} 

template<typename... Args> 
const std::vector<std::size_t> get() { 
    std::vector<std::size_t> sizes; 
    get<sizeof...(Args), Args...>(sizes); 
    return sizes; 
} 
+0

Rokyan很高興看到這樣的替代解決方案,令人驚歎。 –