Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c++ - template metaprogramming: (trait for?) dissecting a specified template into types T<T2,T3 N,T4, ...>

I'm trying to deduce the underlying template type T from a type E = T<T2,T3>. This would for example make it possible to make a template function pair_maker(const E & a) which can be used with one of several similar types of containers. Rough meta code:

template <typename T>
auto pairmaker(const E & a) -> PairContents<E,std::string>::type {
    ContainerPairMaker<E,std::string>::type output;
    ... some code ...
    return output;
}

PairContents<E,std::string>

would transform the type vector<int> into vector<pair(int,std::string)> or whatever<T1> into whatever<pair(T1,std::string)>.

Another similar example of type dissection is for std::array (or similar containers) where I like to figure out the container type to make a new similar array. For example for these kind of functions (this is actual working code now)

template <typename T > 
auto make_some3(const T & a) 
           -> std::array<typename T::value_type,10*std::tuple_size<T>::value>{   
   return std::array<typename T::value_type,10*std::tuple_size<T>::value>{} ;
}

This works fine but what I'm after is to make the explicit use of 'std::array' automatic.

For std::array there's the tuple_size trait which helps, and a similar thing can be used to find the type for any second argument, but again I can't think of anything for finding the container type.

To summarize: what kind of machinery (if any) can be used for cases like these. To which extent is it possible to deal with mixes of template arguments, template-template arguments, any number of arguments, and non-template arguments of unknown types.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an idea:

 template <typename T, typename ...>
 struct tmpl_rebind
 {
     typedef T type;
 };

 template <template <typename ...> class Tmpl, typename ...T, typename ...Args>
 struct tmpl_rebind<Tmpl<T...>, Args...>
 {
     typedef Tmpl<Args...> type;
 };

Usage:

typedef std::vector<int> IV;
typedef typename tmpl_rebind<IV, std::pair<double, std::string>>::type PV;

Now PV = std::vector<std::pair<double, std::string>>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...