提取C++中另一个泛型类型的泛型类型

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

本文关键字:泛型类型 另一个 C++ 提取      更新时间:2023-10-16

假设我有一个类Foo,它使用两种不同的泛型类型,一种是_Type,另一种是_Comparator。已知_Typestd::vectorstd::liststd::string,因此它将有一个类型:T将在vectorlist中;char将在string内。

我的另一个泛型类型_Comparator是一个可选的模板参数,用户可以通过它指定自己的小于函数、函子或lambda函数。如果没有提供任何参数作为第二个模板参数,则应默认为std::less<M>函子,其中类型M应为_Type中包含的元素类型。

我不知道怎么做的语法。

我试过:

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

但无济于事。

使用@Joachim Pileborg在评论中提到的方法,我能够提出以下内容,这使我能够访问_Type的内部类型:

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

并且现在CCD_ 17比较正确的类型而不抱怨。

如果我正确理解你的问题,你可以尝试以下方法:

#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;
}

即,使用外部类来保存"基本"类型(T),使用内部类来保存容器(Type)和比较器。

正如您所说,您只想支持vectorliststring,您可以使用以下内容:

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

这将支持所有具有成员typedef value_type的类型,而vectorliststring都具有成员typedef。

使用可变模板模板参数支持其他类型是可能的,但这会变得更加复杂。