gpt4 book ai didi

c++ - 如何在没有 的情况下声明具有统一类型的元组?

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:45 25 4
gpt4 key购买 nike

我想要一个函数来返回 N foo 的元组s 表示某个值 N(N 不是代码的一部分)。

如果它是 C++14,我可能可以绕过实际上声明任何东西并只使用 auto作为返回类型,但这在 C++11 中不起作用。我不想使用 -> auto decltype因为那将意味着很多的文字,我不妨写,比方说,std::tuple{foo, foo, foo, foo} .

另一种选择是将返回类型设置为 std::array<foo, N> ;这应该可行。不过,我想知道的是,我是否可以在不拉入所有 <array> 的情况下度过难关? ,我实际上并不需要它的功能。

最佳答案

#include <tuple>
#include <utility>
#include <iostream>

namespace detail {

// the concept of N Ts. This is a type generator.
template<class T, std::size_t N>
struct tuple_of_n
{
using rest_tuple = typename tuple_of_n<T, N-1>::type;
using type = decltype(std::tuple_cat(std::declval<std::tuple<T>>(), std::declval<rest_tuple>()));
};

// terminal case where N is 0
template<class T>
struct tuple_of_n<T, 0>
{
using type = std::tuple<>;
};
}

// typedef turns the generator into a type
template<class T, std::size_t N>
using tuple_of_n = typename detail::tuple_of_n<T, N>::type;

int main() {

// test
using two_ints = tuple_of_n<int, 2>;

// proof of equivalency
two_ints is = std::make_tuple(2, 4);

std::cout << std::get<0>(is) << std::endl;
std::cout << std::get<1>(is) << std::endl;

return 0;
}

关于c++ - 如何在没有 <array> 的情况下声明具有统一类型的元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41050025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com