[英]Call right template specialization for each type of a variadic template
I have a function foo()
that takes a list of types T...
and inside calls another (templated) function called do_stuff()
for every element of a vector that is passed in. More specifically, we loop over the vector (of length sizeof...(T)
), and would like to call do_stuff<Ti>()
for vector[i]
, where Ti
is the i
'th type in T...
我有一个函数foo()
,它接受类型T...
的列表,并针对传入的向量的每个元素调用另一个(模板化的)函数do_stuff()
。更具体地说,我们遍历向量(长度sizeof...(T)
),并想对vector[i]
调用do_stuff<Ti>()
,其中Ti
是T...
的第i
个类型T...
The information is available at compile time so I guess this is possible, but how we do it nicely? 该信息在编译时可用,所以我想这是可能的,但是我们如何做到这一点呢?
#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);
}
You can use a C++17 fold expression: 您可以使用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 Godbolt.org上的实时示例
Alternatively, you can avoid the mutable i
variable with std::index_sequence
: 另外,您可以使用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...>{});
}
What about as follows ? 如下呢?
template <typename ... T>
void foo (std::vector<int> const & p)
{
assert(p.size() == sizeof...(T));
using unused = int[];
std::size_t i{ 0u };
(void)unused { 0, ((void)do_stuff<T>(p[i++]), 0)... };
}
If you can use C++17, see the Vittorio Romeo's answer for a more elegant and concise solution. 如果可以使用C ++ 17,请参见Vittorio Romeo的答案,以获取更优雅,更简洁的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.