我试着写一个模板类和输出运算符将其如下:与可变参数模板包类模板输出操作
#include <iostream>
namespace N
{
template< typename ...types >
struct X
{
static_assert((sizeof...(types) != 0), "zero length");
X() = default;
X(X const &) = default;
X(X &&) = default;
template< typename ...args >
//explicit // does not matter
X(args &&...) { ; }
int value = 10;
};
template< typename ...types >
std::ostream &
operator << (std::ostream & out, X<types...> const & x)
{
return out << x.value;
}
} // namespace N
int main()
{
using namespace N;
X<float> /*const*/ x; // `const` does not matter
std::cout << x << std::endl;
return 0;
}
但static_assert
离子提出:
main.cpp:9:5: error: static_assert failed "zero length"
static_assert((sizeof...(types) != 0), "zero length");
^ ~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:32:23: note: in instantiation of template class 'N::X<>' requested here
std::cout << x << std::endl;
^
1 error generated.
如果类模板X
和全局namespace
中定义的operator <<
重载全部相同。我发现,评论using namespace N;
行和替换X<float>
到N::X<float>
解决了这个问题。
如何解释这种行为?原因是什么?
编辑:
我找到了解决办法:是恰克超载operator <<
模板参数如下:
template< typename first, typename ...rest >
std::ostream &
operator << (std::ostream & out, X< first, rest... > const & x)
{
return out << x.value;
}
类的分裂typename ..types
不nessesarily。而且,由于代码的严重膨胀而导致后果并不理想。
使用''\ n''而不是多余的'std :: endl'修复了它。 – Cubbi