是否可以在可变参数模板函数中扩展非变量参数? [英] Is it possible to expand non-variadic arguments in a variadic template function?
问题描述
通过一个例子来解释我的意思可能更容易。想象以下模板:
It is probably easier to explain what I mean by an example. Imagine a following template:
template <class... Args>
std::tuple<Args...> foo();
例如可以这样调用:
auto ret = foo<int, bool>();
但是,如果我想根据可变参数模板参数的数量将其他参数传递给函数,该怎么办?例如,假设我要为每个Args传递字符串文字:
But what if I want to pass additional arguments to the function, based on the number of variadic template arguments? For example, let's say I want to pass a character string literal for every Args:
auto ret = foo<int, bool>("a", "b");
此问题在于,似乎不可能扩展非变量论证,因此以下显然无法编译:
The problem with this, is that it does not seem possible to expand non-variadic arguments, so the following obviously doesn't compile:
template <class... Args>
std::tuple<Args...> foo(const char*... names);
是否有任何明智的实现方法?
Is there any sensible way to implement this?
推荐答案
您可以使用
template <class... Args>
std::tuple<Args...> foo(proxy<Args, const char*>... names);
其中 proxy
是
template<class T, class E>
using proxy = E;
您可以在此处看到以下内容: https://godbolt.org/g/SHBYzy
You can see this in action here: https://godbolt.org/g/SHBYzy
这篇关于是否可以在可变参数模板函数中扩展非变量参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!