[英]How can one construct an object from a parameter pack in a C++ template?
鉴于以下情况,如何从参数包中正确构造未知类型的 object?
template < typename... Types >
auto foo( Types&&... types ) {
auto result = Types{ }; // How should this be done?
// Do stuff with result
return result;
}
我希望模板 function 只能用匹配的类型调用,所以参数包中的所有内容都应该是相同的类型。 例如,如果我需要使用decltype
,我引用哪个单独的项目并不重要(否则注释掉部分中的相关代码将导致编译错误)。
一种复杂但有效的方式:
#include <tuple>
template < typename... Types >
auto foo( Types&&... types ) {
using tup_t = std::tuple<Types...>;
auto result = std::tuple_element_t<0, tup_t>{};
// Do stuff with result
return result;
}
// auto k = foo(); // compile error
auto z = foo(10); // z is 0-initialized int
由于参数包中的所有类型都是相同的,所以可以先使用逗号运算符展开参数包,然后使用decltype
获取最后一个操作数的类型。
template<typename... Types>
auto foo(Types&&... types) {
auto result = decltype((Types{}, ...)){ };
// Do stuff with result
return result;
}
由于参数包中的所有类型都相同,因此可以使用std::common_type_t ,它给出了参数包中所有类型都可以转换为的类型。
template <typename... Types>
auto foo(Types&&... types) {
auto result = std::common_type_t<Types...>{};
// Do stuff with result
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.