繁体   English   中英

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

[英]c++ template function specialization - wrong number of template arguments?

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

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

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’

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

假设您对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);

与一般模板相比,这种重载将是首选。

你所做的不是完全专业化,而是部分专业化,因为你仍然有一个模板,只有一个更专业的模板。 但是,您不能部分专门化函数,因此我们只提供一个新的重载。 对于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)
{
  // ...
}

这个答案与C ++ 11无关

如果您使用的是pre-c ++ 11编译器,则在关闭嵌套模板时不能使用>> 你需要在> s之间留一个空格。

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

以下更有可能奏效:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM