考虑以下简短的程序。
#include <iostream>
template< typename ... Ts >
class foobar
{
static_assert( sizeof...(Ts) > 0 );
};
template< typename ... Ts >
std::ostream& operator<<( std::ostream& o, const foobar< Ts... >& )
{
return o;
}
int main(void)
{
std::cout << "This has nothing to do with foobar" << std::endl;
}
当我们试图编译这个时,我们会得到...
ted@tedscomputer:~/Projects/emptypack$ g++ -o emptypack main.cpp
main.cpp: In instantiation of ‘class foobar<>’:
main.cpp:17:63: required from here
main.cpp:6:34: error: static assertion failed
6 | static_assert( sizeof...(Ts) > 0 );
| ~~~~~~~~~~~~~~^~~
ted@tedscomputer:~/Projects/emptypack$
我知道std::endl
有点奇怪(以至于它实际上拥有自己的StackOverflow标签),但是这里到底出了什么问题?为什么编译器尝试使用空类型参数来实例化我的完全无关的类,失败,并生成一个错误?
更重要的是,每次我编写一个带参数包的类,我是否都需要确保它可以不带任何类型参数进行实例化,即使这对于程序逻辑来说毫无意义,只是为了防止它接近std::endl
?
Ts
为空参数包(https://dev59.com/gVMI5IYBdhLWcg3wDXHi)成为一种替换失败,而不是在实例化类时硬性失败(我认为是为了查找转换构造函数?)。 - Artyer