假设我有一个模板(称为 ExampleTemplate),它接受两个参数:一个容器类型(例如列表、 vector )和一个包含类型(例如 float 、 bool 值等)。因为容器实际上是模板,所以这个模板有一个模板参数。这是我必须写的:
#include <vector>
#include <list>
using namespace std;
template < template <class,class> class C, typename T>
class ExampleTemplate {
C<T,allocator<T> > items;
public:
....
};
main()
{
ExampleTemplate<list,int> a;
ExampleTemplate<vector,float> b;
}
您可能会问“分配器”是什么。好吧,最初,我尝试了显而易见的事情......
template < template <class> class C, typename T>
class ExampleTemplate {
C<T> items;
};
...但不幸的是我发现分配器的默认参数...
vector<T, Alloc>
list<T, Alloc>
etc
...必须在模板声明中明确“保留”。 如您所见,这使代码更难看,并迫使我重现模板参数的默认值(在本例中为分配器)。
这是不好。
编辑:这个问题不是关于容器的具体问题——它是关于“模板参数中的默认值”,上面只是一个例子。取决于 STL 容器具有“::value_type”的知识的答案不是我所追求的。想想一般的问题:如果我需要在模板ExampleTemplate 中使用模板参数C,那么在ExampleTemplate 的主体中,我是否必须在使用时重现C 的默认参数?如果我必须这样做,那不会引入不必要的重复和其他问题(在这种情况下,C 是 STL 容器,可移植性问题 - 例如“分配器”)?
最佳答案
也许你更喜欢这个:
#include <vector>
#include <list>
using namespace std;
template <class Container>
class ForExamplePurposes {
typedef typename Container::value_type T;
Container items;
public:
};
int main()
{
ForExamplePurposes< list<int> > a;
ForExamplePurposes< vector<float> > b;
}
这使用“静态 duck typing”。它也更灵活一点,因为它不强制 Container 类型支持 STL 的 Allocator 概念。
也许使用 type traits成语可以给你一条出路:
#include <vector>
#include <list>
using namespace std;
struct MyFunkyContainer
{
typedef int funky_type;
// ... rest of custom container declaration
};
// General case assumes STL-compatible container
template <class Container>
struct ValueTypeOf
{
typedef typename Container::value_type type;
};
// Specialization for MyFunkyContainer
template <>
struct ValueTypeOf<MyFunkyContainer>
{
typedef MyFunkyContainer::funky_type type;
};
template <class Container>
class ForExamplePurposes {
typedef typename ValueTypeOf<Container>::type T;
Container items;
public:
};
int main()
{
ForExamplePurposes< list<int> > a;
ForExamplePurposes< vector<float> > b;
ForExamplePurposes< MyFunkyContainer > c;
}
想要将 ForExamplePurposes
与不符合 STL 的容器一起使用的人需要专门化 ValueTypeOf
特征类。
关于c++ - 带有模板参数的模板中的默认值 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5301706/