我正在尝试使用 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 *>
关于c++ - 将指针和 const 添加到 std::tuple<Types...>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41229598/