来自可变参数模板的shared_ptr元组?
以以下代码段为基础:
template<typename Type1, typename Type2>
auto Foo() {
std::tuple<std::shared_ptr<Type1>, std::shared_ptr<Type2>> example;
}
使用可变参数模板时,我应该如何创建共享指针元组?
template<typename... Types>
auto Foo() {
// How to create the tuple?
}
这里有大量与元组和可变参数模板相关的问题。有些人似乎解决了这个问题(link1,link2),但仍然觉得太复杂(老实说,答案超出了我的脑海,但很可能是最简单的方法)。
我的尝试使用了递归模板 and std::tuple_cat,但这会在此过程中创建许多“子元组”,这远非理想。
简而言之:是否有“更简单”或“更直接”的方法来解决这个问题?不需要多个函数、递归调用等等的东西,有点像std::tuple<std::shared_ptr<Types...>>?
回答
展开包:
#include <tuple>
#include <memory>
#include <type_traits>
template<typename... Types>
auto Foo() {
using tup = std::tuple<std::shared_ptr<Types>...>;
return tup{};
}
int main() {
auto f = Foo<int,double>();
static_assert( std::is_same_v< std::tuple<std::shared_ptr<int>,std::shared_ptr<double>>,decltype(f)>);
}
为方便起见,您可以使用别名:
#include <tuple>
#include <memory>
#include <type_traits>
template <typename...Types>
using SharedTuple = std::tuple<std::shared_ptr<Types>...>;
int main() {
static_assert( std::is_same_v< std::tuple<std::shared_ptr<int>,std::shared_ptr<double>>,SharedTuple<int,double>>);
}