Jyt*_*tug 2 c++ templates partial-specialization c++11
我正在尝试使用C++11模板的魔力来实现以下目标:
假设我有这样的类型:
using my_types = std::tuple<char, int, float>;
Run Code Online (Sandbox Code Playgroud)
有了这个,我想得到一个指向两者const而不是值的指针元组,即:
std::tuple<char *, int *, float *, const char *, const int *, const float *>;
Run Code Online (Sandbox Code Playgroud)
我现在的解决方案:
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...>;
};
Run Code Online (Sandbox Code Playgroud)
这给了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...>;
};
Run Code Online (Sandbox Code Playgroud)
这工作,但我想这得到多一点的一般:我想有一个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...
>;
};
Run Code Online (Sandbox Code Playgroud)
然后
add_ptr<std::add_const, my_types>::type
Run Code Online (Sandbox Code Playgroud)
将会
std::tuple<char *, int *, float *, char const *, int const *, float const *>
Run Code Online (Sandbox Code Playgroud)