[英]Add pointer and const to std::tuple<Types…>
I'm trying to achieve the following using the magic of C++11
templates: 我正在尝试使用
C++11
模板实现以下目的:
Suppose I have a type like this: 假设我有一个像这样的类型:
using my_types = std::tuple<char, int, float>;
Having this, I'd like to get a tuple of pointers to both const
and not values, ie: 有了这个,我想得到一个指向
const
而不是值的指针的元组,即:
std::tuple<char *, int *, float *, const char *, const int *, const float *>;
My solution for now: 我现在的解决方案:
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...>;
};
This gives std::tuple<types, const types>
. 这给出了
std::tuple<types, const types>
。 To get pointers, I can use: 要获取指针,我可以使用:
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...>;
};
This works, but I would like this to get a little more general: I want to have a template<trait, Types...> add_ptr
that gives me pointers to both Types...
and trait<Types>::type...
, so the usage could be the following: 这行得通,但是我希望这变得更笼统:我想有一个
template<trait, Types...> add_ptr
,它为我提供了指向Types...
和trait<Types>::type...
指针trait<Types>::type...
,因此用法可能如下:
add_ptr<std::add_const, my_types>
is the tuple i mentioned before add_ptr<std::add_volatile, my_types>
gives std::tuple<char *, volatile char *, ...>
add_ptr<std::add_const, my_types>
是我在add_ptr<std::add_volatile, my_types>
给出std::tuple<char *, volatile char *, ...>
之前提到的元组
I would appreciate some hints on how this can be achieved. 我将对如何实现这一目标表示感谢。 I'm not yet a template magician and would appreciate some help
我还不是模板魔术师,不胜感激
Use a template template-parameter 使用模板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...
>;
};
Then 然后
add_ptr<std::add_const, my_types>::type
will be 将会
std::tuple<char *, int *, float *, char const *, int const *, float const *>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.