c++ - 为每种类型的可变参数模板调用正确的模板特化

标签 c++ variadic-templates template-meta-programming

我有一个函数 foo()接受类型列表 T...并在内部调用另一个名为 do_stuff() 的(模板化)函数对于传入的 vector 的每个元素。更具体地说,我们遍历 vector (长度为 sizeof...(T) ),并希望调用 do_stuff<Ti>()对于 vector[i] , 其中TiiT... 中输入第

信息在编译时可用,所以我想这是可能的,但我们如何做得很好?

#include <iostream>
#include <string>
#include <vector>
#include <cassert>

template <typename T>
T do_stuff(int param);

template <>
int do_stuff(int param)
{
    return int(100);
}

template <>
std::string do_stuff(int param)
{
    return std::string("foo");
}

template <typename... T>
void foo(const std::vector<int>& p)
{
    assert(p.size() == sizeof...(T));
    for (int i = 0; i < p.size(); ++i)
    {
        // Won't compile as T is not specified:
        //do_stuff(p[i]);
        // How do we choose the right T, in this case Ti from T...?
    }
}

int main()
{
    std::vector<int> params = { 0,1,0,5 };
    foo<int, std::string, std::string, int>(params);
}

最佳答案

您可以使用 C++17 折叠表达式:

template <typename... T>
void foo(const std::vector<int>& p)
{
    assert(p.size() == sizeof...(T));

    std::size_t i{};
    (do_stuff<T>(p[i++]), ...);
}

live example on godbolt.org


或者,您可以使用 std::index_sequence 避免可变的 i 变量:

template <typename... T>
void foo(const std::vector<int>& p)
{
    assert(p.size() == sizeof...(T));

    [&p]<auto... Is>(std::index_sequence<Is...>)
    {
        (do_stuff<T>(p[Is]), ...);
    }(std::index_sequence_for<T...>{});
}

live example on godbolt.org

关于c++ - 为每种类型的可变参数模板调用正确的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872749/

相关文章:

VB.NET 重命名文件和重新标记/编辑图像元数据/元标记

c++ - 我如何获得指向已推导的模板函数的指针?

C++ 初始化列表和可变参数模板

c++ - 如何在 Mixin 类中按类型返回组件?

c++ - 在模板参数中使用时,type_trait<T>{} 中的 {} 的作用是什么?

c++ - 为什么 gcc 提示 "error: type ' intT' of template argument '0' depends on a template parameter”?

c++ - 纹理描述中的Non Redundant LBP是什么?

python - 从 C++ exe 中获取输出并在 Python 中实时处理它

c++ - 从非常大的文件中解析每四行的最有效方法

c++ - 是否有理由更喜欢一个变量的多个 unordered_map 而不是一个结构?