提取C++中另一个泛型类型的泛型类型
Extract the generic type of another generic type in C++
假设我有一个类Foo,它使用两种不同的泛型类型,一种是_Type
,另一种是_Comparator
。已知_Type
是std::vector
、std::list
或std::string
,因此它将有一个类型:T
将在vector
和list
中;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
)和比较器。
正如您所说,您只想支持vector
、list
和string
,您可以使用以下内容:
template <typename T, typename Compare = std::less<typename T::value_type>>
这将支持所有具有成员typedef value_type
的类型,而vector
、list
和string
都具有成员typedef。
使用可变模板模板参数支持其他类型是可能的,但这会变得更加复杂。
相关文章:
- 使用泛型类型推送到堆栈时出现问题
- 如何在容器中指定模板化别名的泛型类型
- 具有模板专用化的泛型类型转换
- C++存储泛型 T 类型类的向量
- 如何在C++中返回没有模板的泛型类型?
- 如何在带有约束 (C++) 的函数中使用泛型类型
- 模板函数重载(泛型类型与模板模板类型)选择正确的重载
- 泛型类型别名,它们彼此不兼容
- 泛型类型转换
- 重载泛型类型的模板类时检查运算符=时的自赋值
- 在C++中,如何根据类中的参数返回不同的泛型类型
- C++错误 C2227:'->looseHealth'左侧必须指向类/结构/联合/泛型类型
- 使用泛型类型显式实例化函数模板
- 函数模板中的无效转换错误,返回值取决于其泛型类型
- 如何确保 "<<" 运算符适用于模板化 ADT 定义中的任何泛型类型?
- 如何编写一个可以以类型安全的方式迭代泛型类型的函数
- 如何编写一个可以迭代泛型类型的函数
- 使用C++生成泛型类型-一个具有共享实现的模板
- 提取C++中另一个泛型类型的泛型类型
- (Boost)为什么我们需要一个泛型类型