c++ - 将指针和 const 添加到 std::tuple<Types...>

标签 c++ c++11 templates partial-specialization

我正在尝试使用 C++11 的魔力来实现以下目标模板:

假设我有这样的类型:

using my_types = std::tuple<char, int, float>;

有了这个,我想获得一个指向 const指针元组而不是值,即:

std::tuple<char *, int *, float *, const char *, const int *, const float *>;

我现在的解决方案:

template<typename T>
struct include_const {};

template<typename... Types>
struct include_const<std::tuple<Types...>> {
  using type = std::tuple<Types..., typename std::add_const<Types>::type...>;
};

这给出了 std::tuple<types, const types> 。要获取指针,我可以使用:

template<typename T>
struct add_ptr {};

template<typename... Types>
struct add_ptr<std::tuple<Types...>> {
  using type = std::tuple<typename std::add_pointer<Types>::type...>;
};

这可行,但我希望它更通用一些:我想要一个 template<trait, Types...> add_ptr这给了我指向 Types... 的指针和trait<Types>::type... ,因此用法可能如下:

add_ptr<std::add_const, my_types>是我之前提到的元组 add_ptr<std::add_volatile, my_types>给出std::tuple<char *, volatile char *, ...>

我希望得到一些关于如何实现这一目标的提示。我还不是模板魔术师,希望得到一些帮助

最佳答案

使用模板模板参数

template<template<typename> class Trait, typename U>
struct add_ptr {};

template<template<typename> class Trait, typename... Types>
struct add_ptr<Trait, std::tuple<Types...>> {
  using type = std::tuple<
                    typename std::add_pointer<Types>::type...,
                    typename std::add_pointer<
                        typename Trait<Types>::type
                    >::type...
                >;
};

然后

add_ptr<std::add_const, my_types>::type

将会

std::tuple<char *, int *, float *, char const *, int const *, float const *>

Live demo

关于c++ - 将指针和 const 添加到 std::tuple<Types...>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41229598/

相关文章:

c++ - 如何在 C++ 中创建动态分配的二维结构数组?

c++ - 如何修复 "Invalid operands to binary expression "类“到 "class"”错误 (repl.it)

c++ - STL 容器模板

c++ - 无论如何,有没有根据 C++ 中参数的成员来专门化模板?

C++ 模板, undefined reference

c++ - 加速 C++ : Can I substitute raw pointers for smart pointers?

c++ - 无法从类型 x 转换为类型 x?

c++ - 在 C++ 中解包嵌套元组

c++ - 创建购物车

c++ - 如何在 C++ 中解析数组以查找重复项