c++ - 带有模板参数的模板中的默认值 (C++)

标签 c++ templates

假设我有一个模板(称为 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/

相关文章:

templates - 如何在flask jinja2模板中加密id

c++ - 使用 QGraphicsBlurEffect 进行 QImage 变换

c++ - C++ 中的异步线程安全日志记录(无互斥量)

c++ - 很难在 multimap<Class object, enum> 上使用 max_element(也有 min_element)

c++ - 了解引用绑定(bind)

javascript - Vuejs未定义属性错误但已定义

c++ - 有没有办法将文字字符串放入 <char...> 模板中?

c++ - std::list.end() 不返回 "past-the-end"迭代器

c++ - 无法理解使用模板的函数定义

c++ - 从模板化父类中的派生内部类访问 protected 成员变量