简体   繁体   中英

Given a templated class, is there a way to get the "base"/untemplated type?

Pretty straightforward, but maybe not possible: Given some T<some_type> , is there a way to get T ? A better example with code here:

template<class T>
struct parametrized_class{
   
};

template<class T>
using make_floaty = T<float>; // this doesn't compile since T is not the "base" type

int main() {
   using int_class = parametrized_class<int>;
   using float_class = make_floaty<int_class>;
}

I don't think it is, but I want to make sure.

You definitely can, although templates not being first-class citizens makes it a bit tricky:

template <class T>
struct make_floaty;

template <template <class> class Template, class T>
struct make_floaty<Template<T>> {
    using type = Template<float>;
};

template <class T>
using make_floaty_t = typename make_floaty<T>::type;

See it live on Wandbox

By using template template parameters you can write a trait that given an instantiation of a template and another type it "returns" an instantiation with that other type:

template <typename OLDINSTANTIATION,typename NEWPARAMETER>
struct replace_template_parameter;

template <template<typename...> class T,typename OLDPARAM,typename NEWPARAM>
struct replace_template_parameter< T<OLDPARAM>,NEWPARAM> {
    using type = T<NEWPARAM>;
};

make_floaty can then be written as:

template <class T>
using make_floaty = typename replace_template_parameter< T,float>::type;

Complete Example :

#include <iostream>
#include <type_traits>

template<class T> struct parametrized_class{};

template <typename OLDINSTANTIATION,typename NEWPARAMETER> struct replace_template_parameter;

template <template<typename...> class T,typename OLDPARAM,typename NEWPARAM>
struct replace_template_parameter< T<OLDPARAM>,NEWPARAM> {
    using type = T<NEWPARAM>;
};

template <class T> using make_floaty = typename replace_template_parameter< T,float>::type;

int main() {
   using int_class = parametrized_class<int>;
   using float_class = make_floaty<int_class>;
   std::cout << std::is_same< float_class, parametrized_class<float>>::value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM