我有一个函数 foo()
接受类型列表 T...
并在内部调用另一个名为 do_stuff()
的(模板化)函数对于传入的 vector 的每个元素。更具体地说,我们遍历 vector (长度为 sizeof...(T)
),并希望调用 do_stuff<Ti>()
对于 vector[i]
, 其中Ti
是i
在 T...
中输入第
信息在编译时可用,所以我想这是可能的,但我们如何做得很好?
#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++]), ...);
}
或者,您可以使用 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...>{});
}
关于c++ - 为每种类型的可变参数模板调用正确的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872749/