c++ - 类的 index_sequence 用法

标签 c++ templates c++14 template-meta-programming

我想创建一个接受以下输入的类:

1,make_tuple('A',2,'B')

在类内部有一个静态类型的元组:

std::tuple<int,char,int,char>

和内容:

{1,'A',2,'B'}

应该创建。

有点像这样——但不是函数返回元组——它应该是一个元组,它是一个类的成员变量:

http://ideone.com/iu1wm5

我知道我手动声明了元组 - 但我打算在弄清楚如何执行此操作后修复它。

我还没有找到任何索引和模板类的示例 - 如果您有这样一个示例的链接,那也很好。

我知道http://cpptruths.blogspot.dk/2012/06/perfect-forwarding-of-parameter-groups.html但他使用的是 vector ,而不是元组。

最佳答案

是这样的吗?

#include <iostream>
#include <string>
#include <tuple>
#include <typeinfo>
#include <cstddef>

template<class Ch, class Tr, class Tuple, std::size_t... Is>
void print_tuple_impl(std::basic_ostream<Ch, Tr>& os,
                      const Tuple & t,
                      std::index_sequence<Is...>)
{
    using swallow = int[]; // guaranties left to right order
    (void)swallow {
        0, (void(os << (Is == 0 ? "" : ", ") << std::get<Is>(t)), 0)...
    };
}

template<class Ch, class Tr, class... Args>
auto operator<<(std::basic_ostream<Ch, Tr>& os, const std::tuple<Args...>& t)
-> std::basic_ostream<Ch, Tr>&
{
    os << "(";
    print_tuple_impl(os, t, std::index_sequence_for<Args...>{});
    return os << ")";

}

template<class Tuple>
struct X {
    void print() const {
        std::cout << _tuple << std::endl;
    }
    Tuple _tuple;
};

template<class First, class...Rest>
struct myClass
{
    std::tuple<First, Rest...> myTuple;

    myClass(First parameterOne, std::tuple<Rest...> param2)
    : myTuple(std::tuple_cat(std::make_tuple(parameterOne),
                             param2))
    {

    }

    void print() const {
        std::cout << myTuple << std::endl;
    }
};

template<class First, class...Rest>
auto make_myClass(const First& f, const std::tuple<Rest...> rest)
-> myClass<First, Rest...>
{
    return { f, rest };
}

using namespace std;

int main()
{
    auto mine = make_myClass(1, make_tuple('a', 4));
    mine.print();

    return 0;
}

关于c++ - 类的 index_sequence 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211207/

相关文章:

使用 Boost 函数和 C++ 类方法的 C++ 回调

c++ - 在 C++ 中强制删除 std::shared_ptr

c++ - 在参数中使用模板<>

c++ - 基本类型的 std::vector 的部分类模板特化

c++ - 使用成员函数创建 std::function 不编译

c++ - C++14 中的 RVO 和删除的移动构造函数

c++ - Qt:交换 QGraphicsRectItem 位置的最佳方法是什么

c++ - 在用 C++ 编写字符串的过程中按 'Enter'

templates - 返回不同输入范围时函数返回类型不匹配的现象

c - 从上一个索引到当前索引搜索数组