你可以只使用
static_assert
为了实现这一点:
void f(auto&& r)
{
static_assert(r.size() == 2, "Only ranges of size 2 supported");
std::cout << r.size() << std::endl;
}
For
f(std::array<int, 3>{5, 7, 11});
GCC给出以下输出:
<source>: In instantiation of 'void f(auto:10&&) [with auto:10 = std::array<int, 3>]':
<source>:18:6: required from here
18 | f(std::array<int, 3>{5, 7, 11});
| ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:12:28: error: static assertion failed: Only ranges of size 2 supported
12 | static_assert(r.size() == 2, "Only ranges of size 2 supported");
| ~~~~~~~~~^~~~
<source>:12:28: note: the comparison reduces to '(3 == 2)'
Compiler returned: 1