我真的不知道这个名字叫什么,请原谅。我认为最好以身作则。
void foo(std::pair<std::string, T>, std::pair<std::string, U>, std::pair<std::string, Z>, ...);
其中T,U和Z可以是许多类型,但是列表不断使用可变数量的参数。我知道您可以使用参数包,并假设它们沿着这条线传递对象,但是当您调用该函数时,就无法调用成对的聚合初始化程序。
template<typename ...args>
void foo(args... values);
//the following isn't allowed, cause it doesn't know the type. (this is what I want it to look like)
foo({"hi",5}, {"hello", true});
甚至有可能我要做什么?任何帮助,将不胜感激。
从C ++ 17开始,您可以利用CTAD(Class Template Argument Deduction)并使用std::string
的operator""s
具有
template<typename ...args>
void foo(args... values) {}
// or to make sure pair types are provided
//template<typename ...args>
//void foo(std::pair<std::string, args>... values) {}
int main()
{
using std::pair;
using namespace std::string_literals;
foo(pair{"hi"s, 5}, pair{"hello"s, true});
}
您可能会执行以下操作以将参数约束为对:
template<typename ...Ts>
void foo(std::pair<std::string, Ts>... values);
通话必须类似于:
foo(std::pair{std::string("hi"),5}, std::pair{std::string("hello"), true});
foo<int, bool>({"hi",5}, {"hello", true});