【问题标题】:Getting the size of each type of the parameter pack?获取每种类型参数包的大小?
【发布时间】:2016-11-17 21:23:05
【问题描述】:

在网上搜索了一整天未成功的实用解决方案来解决我的问题后,我决定在这里发布我的问题,以阐明我的目标,我提供了这个简单的代码:

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 }

任何建议或解决方案都是相当重要的。

【问题讨论】:

    标签: c++ templates variadic


    【解决方案1】:

    我建议为此使用std::array

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

    【讨论】:

    • 作为@W.F.提到您的回答提供了我正在寻找的实用解决方案,我非常感激。
    • 在同一行代码中使用sizeofsizeof... 的绝佳示例。
    【解决方案2】:

    你可以用解压后的大小初始化向量:

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

    demo

    【讨论】:

    • 感谢您的帮助。
    • @AmraneAbdelkader 还考虑将结果类型更改为数组(它具有已知的编译时间大小)这将允许函数为 constexpr...
    • @W.F.对,这对你的提议很重要。
    【解决方案3】:

    还有另一种可能的解决方案说明了如何使用 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;
    }
    

    【讨论】:

    • Rokyan 看到这样的替代解决方案总是很高兴,太棒了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多