获取每种参数包的大小?

Amr*_*der 2 c++ templates variadic

经过漫长的一天不成功的网上搜索找到解决问题的实用解决方案后,我决定在这里发布我的问题,以澄清我的目标,我提供了这个简单的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

当我在这段代码中调用此函数模板时:

// platform x86
std::vector<SIZE_T> tempVactor;
tempVactor = GetTypesSize<char, short, int>(); 
Run Code Online (Sandbox Code Playgroud)

tempVactor应该是的元素{ 1, 2, 4 }.

任何建议或解决方案都相当可观.

krz*_*zaq 6

您可以使用解压缩的大小初始化向量:

template<typename... types>
std::vector<size_t> GetTypesSize()
{
    return { sizeof(types)... };
}
Run Code Online (Sandbox Code Playgroud)

演示

  • @AmraneAbdelkader还考虑将结果类型更改为数组(它具有已知大小的编译时间)这将允许函数为constexpr ... (3认同)

Gui*_*cot 5

我建议std::array为此使用:

template<typename... Types>
constexpr auto GetTypesSize() {
    return std::array<std::size_t, sizeof...(Types)>{sizeof(Types)...};
}
Run Code Online (Sandbox Code Playgroud)

  • 在同一行代码中使用的`sizeof`和`sizeof ...`的绝佳示例。 (2认同)