c ++模板函数专门化 - 错误的模板参数数量?

时间:2011-10-11 04:00:08

标签: c++ templates

好的,所以我只是在学习模板。无论如何,我可能(最绝对)做错了什么,但问题出在这里:

我的第一个模板函数声明如下:

template<typename T>
std::ostream& printFormatted(T const& container, std::ostream& os = std::cout) {
    //...
}

然后我应该为地图实现一个专门的案例,所以这就是我试图做的事情:

template<>
std::ostream& printFormatted<std::map<typename key, typename value>>(std::map<typename key, typename value> const& container, std::ostream& os = std::cout) {
    //...
}

我可能在使用我的键/值变量时出错了,不确定,但无论如何,在尝试编译时我收到错误消息:

error: wrong number of template arguments (1, should be 4)
error: provided for ‘template<class _Key, class _Tp, class _Compare, class _Allocator> class std::__debug::map’

显然,我对模板或地图有些不了解?有人请帮忙吗?

3 个答案:

答案 0 :(得分:3)

假设您使用keyvalue作为安置点,则无法使用关键字typename内联声明模板参数。也就是说,Foo<typename T>始终无效 - 但不要误认为Foo<typename T::bar>完全不同。专业化的语法如下:

// Declare template parameters up front
template<typename Key, typename Value>
std::ostream&
printFormatted<std::map<Key, Value> >(std::map<Key, Value> const& container, std::ostream& os = std::cout);

但这不起作用,因为它是部分特化,而且不允许使用功能模板。改为使用重载:

template<typename Key, typename Value>
std::ostream&
printFormatted(std::map<Key, Value> const& container, std::ostream& os = std::cout);

这种重载优先于更通用的模板。

答案 1 :(得分:3)

你所做的不是完全专业化,而是部分专业化,因为你仍然有一个模板,只有一个更专业的模板。但是,您不能部分专门化函数,因此我们只提供一个新的重载。对于std::map,您需要四个模板参数(正如错误消息有用地告诉您):

template <typename K, typename V, typename Comp, typename Alloc>
std::ostream & printFormatted(const std::map<K,V,Comp,Alloc> & m,
                              std::ostream & o = std::cout)
{
  // ...
}

答案 2 :(得分:0)

此答案与C ++ 11无关

如果您使用的是pre-c ++ 11编译器,则在关闭嵌套模板时无法使用>>。您需要>之间的空格。

C ++将>>视为与>不同的标记,编译器不会使用它来关闭模板。您需要一个空格,以便编译器看到>后跟>

以下内容更有可能发挥作用:

template<>
std::ostream& printFormatted<std::map<typename key, typename value> >(std::map<typename         key, typename value> const& container, std::ostream& os = std::cout) {
    //...
}
相关问题