[英]Add pointer and const to std::tuple<Types…>
我正在尝试使用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...
指针trait<Types>::type...
,因此用法可能如下:
add_ptr<std::add_const, my_types>
是我在add_ptr<std::add_volatile, my_types>
给出std::tuple<char *, volatile char *, ...>
之前提到的元组
我将对如何实现这一目标表示感谢。 我还不是模板魔术师,不胜感激
使用模板template-parameter
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 *>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.