c ++模板函数专门化 - 模板参数数错误? [英] c++ template function specialization - wrong number of template arguments?

查看:333
本文介绍了c ++模板函数专门化 - 模板参数数错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Okay, so I'm just learning about templates. Anyways, I'm probably (most definitely) doing something wrong, but here's the problem:

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

My first template function is declared like this:

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

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

Then I'm supposed to implement a specialized case for maps, so this is what I tried to do:

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



我可能会错误地使用键/值变量,不确定,但无论如何,当试图编译我得到错误消息:

I might be making a mistake with my key/value variables, not sure, but regardless, when trying to compile I get the error message:

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’

显然有些东西我不明白模板或地图?有人请帮忙吗?

Clearly there's something I don't understand about templates or maps? Someone please help?

推荐答案

假设您使用 c $ c> value 意味着是placeholers,不能使用关键字 typename 来声明模板参数。也就是说, Foo< typename T> 总是无效的,但不能被 Foo< typename T :: bar& code>这是完全不同的。专用化语法如下:

Assuming your uses of key and value are meant to be placeholers, you cannot declare template parameters inline with the keyword typename. That is to say, Foo<typename T> is always invalid -- but not to be mistaken with Foo<typename T::bar> which is different altogether. The syntax for specialization looks like:

// 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);

但这不会工作,因为它是一个部分不允许用于函数模板。使用重载:

but that wouldn't work because it's a partial specialization and those are not allowed for function templates. Use overloading instead:

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

此重载将优先于更一般的模板。

This overload will be preferred over the more general template.

这篇关于c ++模板函数专门化 - 模板参数数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆