Extract the generic type of another generic type in C ++

Let's say I have a class Foo that uses two different types, one - _Typeand the other - _Comparator. _Typeknown as std::vector, std::listor std::string, therefore, it will have a type inside it: it Twill be within vectorand list; charwill be within string.

My other generic type _Comparatoris an optional template parameter whereby a user can specify his own function less than a function, functor or lambda. If no argument is specified as the second parameter of the template, it should use a functor by default std::less<M>, in which the type Mmust be the type of the elements contained in _Type.

I do not know the syntax of how to do this.

I tried:

template <typename _Type<T>, typename _Comparator = less<T> >

to no avail.

+4
source share
3 answers

Using the approach mentioned by @Joachim Pileborg in the comments, I was able to come up with the following, which allowed me to access the internal type _Type:

template <typename _Type, 
    typename _Comparator = less<typename _Type:: value_type> >
class Foo
{
    public:
        // some methods
    private:
        _Type sequence;
        _Comparator comparator;
};

and now std::lesscompares the correct types without complaint.

+2
source

If I understand your question correctly, you can try something like:

#include <iostream>
#include <vector>
#include <list>
#include <typeinfo>

template <typename T>
class holder
{
public:
    template <typename Type = std::vector<T>, typename Comparator = std::less<T> >
    class impl
    {
    public:
        impl() {std::cout << typeid(s).name() << std::endl; }
        Type s;
    };

} ;

int main()
{
    holder<int>::impl<> holder_of_int_vectors;
    holder<int>::impl<std::list<int> > holder_of_int_lists;
    holder<int>::impl<std::list<int>, std::greater<int> > holder_of_int_lists_with_greater;
}

those. use an external class to store the "base" type ( T) and the internal one for the container ( Type) and comparator.

0
source

, vector, list string, :

template <typename T, typename Compare = std::less<typename T::value_type>>

It will support all who have typedef member value_typethat vector, listand stringeveryone is doing.

It is possible to support other types using the parameters of the varadic template template, but it becomes much more complex.

0
source

Source: https://habr.com/ru/post/1537882/


All Articles