initialization_list 中需要传递不同的类型
The need to pass different types in the initialization_list
我正在寻找一种基于模板的方法来在 initialization_list(s) 中传递任意数量的参数。
类似于:
func({0, 1}, {0, 2.0f}, {0, "boo"}, ...);
或
func({{0, 1}, {0, 2.0f}, {0, "boo", ...}});
同时我希望能够检查每个(内部)大括号中第二个参数的类型。也许得到 sizeof(T)
也许做一些 if constexpr(std::is_same<T, ...>::value)
匹配。
可能吗?如果是这样,func()
的定义会是什么样子?
让f
取std::initializer_list<std::pair<std::any, std::any> >
:
void f(std::initializer_list<std::pair<std::any, std::any> > il) {
for (auto it = il.begin(); it != il.end(); ++it) {
const std::type_info& type1 = it->first.type();
const std::type_info& type2 = it->second.type();
if (type1 == typeid(int)) {
int val1 = std::any_cast<int>(it->first);
}
// ...
}
}
如果您只有几种可能的类型,您可以使用 std::variant<int, float, /*e.g.; etc. */>
而不是 std::any
。
我正在寻找一种基于模板的方法来在 initialization_list(s) 中传递任意数量的参数。
类似于:
func({0, 1}, {0, 2.0f}, {0, "boo"}, ...);
或
func({{0, 1}, {0, 2.0f}, {0, "boo", ...}});
同时我希望能够检查每个(内部)大括号中第二个参数的类型。也许得到 sizeof(T)
也许做一些 if constexpr(std::is_same<T, ...>::value)
匹配。
可能吗?如果是这样,func()
的定义会是什么样子?
让f
取std::initializer_list<std::pair<std::any, std::any> >
:
void f(std::initializer_list<std::pair<std::any, std::any> > il) {
for (auto it = il.begin(); it != il.end(); ++it) {
const std::type_info& type1 = it->first.type();
const std::type_info& type2 = it->second.type();
if (type1 == typeid(int)) {
int val1 = std::any_cast<int>(it->first);
}
// ...
}
}
如果您只有几种可能的类型,您可以使用 std::variant<int, float, /*e.g.; etc. */>
而不是 std::any
。