Reputation: 8636
I am looking here https://github.com/abseil/abseil-cpp/blob/master/absl/types/span.h#L673
template <int&... ExplicitArgumentBarrier, typename T>
constexpr Span<T> MakeSpan(T* ptr, size_t size) noexcept {
return Span<T>(ptr, size);
}
I do not understand this function. What is int&... ExplicitArgumentBarrier
doing?
It isn't used in the function so I am not able to figure out why its being used.
An example to show what 'trick' this is and why it is used would be greatly appreciated.
Upvotes: 3
Views: 653
Reputation: 206627
In a comment, you asked,
i dont quite understand - how, according to you, should
MakeSpan
be called?
Here's a demonstrative program that does not use MakeSpan
.
template <typename ... T, typename T2> void foo(T2 arg) {}
template <int ... N, typename T2> void bar(T2 arg) {}
int main()
{
foo<int, int>(0); // T2 is deduced to be int
foo(0); // T2 is still deduced to be int
foo<int, int>(10.5); // T2 is deduced to be double
foo(10.5); // T2 is still deduced to be double
bar<10, 20, 30>(1); // T2 is deduced to be int
bar(1); // T2 is still deduced to be int
bar<10, 20, 30>(1.2); // T2 is deduced to be double
bar(1.2); // T2 is still deduced to be double
}
A function call that involves MakeSpan
would look like:
int a;
int b;
auto s1 = MakeSpan(20); // T is deduced to be int
auto s1 = MakeSpan<a, b>(20); // T is still deduced to be int
All the explicitly specified template parameters are ignored. The type of argument(s) is always deduced.
Upvotes: 2
Reputation: 10939
A common pattern you find in bad code is the usage of explicit template arguments in function templates which would otherwise perform template argument deduction, e.g.
std::make_pair<int,std::string>(1729, "Hello World!");
This is superfluous and in this case the explicit type for the second argument is even different from the type that would have been deduced.
To prevent people from doing so, you can just put a variadic bogus template argument in front of the argument which is to be deduced, so that nobody can ever explicitly name those arguments.
The developers apparently chose int&...
as the type for the bogus argument but it could have been any other thing (another type as well) and to improve readability of the code they also gave it a name, ExplicitArgumentBarrier
, which should make sense now.
Upvotes: 11