簡體   English   中英

將指針和const添加到std :: tuple <Types…>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM