我有一个在类型参数和参数包上模板化的类,并且对这种类型的类型推导感到困惑;在编写输出流操作符时,我发现一个参数包operator<<
不会与模板类的类型和包参数匹配:
#include <iostream>
template<class T, class... Ts>
struct foo
{ /* ... */ };
template< class... Ts >
std::ostream& operator<<( std::ostream& os, const foo<Ts...>& )
{
return os << 42;
}
int main()
{
std::cout << foo<int>();
}
这无法在 gcc-4.7.2 和 clang-3.0 上编译,所以我想我误解了这里的规则。
gcc 说(其中第 16 行是输出流调用):
t.cpp:16:28: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/iostream:40:0,
from t.cpp:1:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/ostream:600:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = foo<int>]’
铿锵声 说:
t.cpp:16:16: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'foo<int>')
std::cout << foo<int>();
~~~~~~~~~ ^ ~~~~~~~~~~
[--- snip: lots of non-viable candidates from standard library ---]
t.cpp:8:19: note: candidate template ignored: substitution failure [with Ts = <>]
std::ostream& operator<<( std::ostream& os, const foo<Ts...>& )
^
有人可以告诉我为什么operator<<
不能将参数包推导出为类型参数和参数包foo
吗?