Reputation: 5257
Examples where I have seen this:
std::cout << std::plus<>{}(a, b) << '\n';
in the question here.
std::hash<T>{}(54879)
And others, I can't find them right now.
I know that object{}
or object()
calls the default ctor, and object{val}
or object(val1,val2)
calls a constructor with parameters. And object<>{}
or object<T>()
explicitly specifies any type parameter(s) for the object. But what does this mean when all those are used together? I can't find an article or webpage explaining this either, or I may be missing something. What is it?
Upvotes: 2
Views: 571
Reputation: 7202
What you're seeing is the creation of a temporary functor just to invoke its function call operator. Assuming the class has an overload of the function call operator:
template<typename T>
struct myclass {
int operator()(int arg1, int arg2);
};
Then the snippet x = myclass<SomeType>{}(val1, val2);
does the following things:
myclass<SomeType>
by calling the default constructor due to the uniform initializer {}
.operator()
on that temporary object, in this case supplying val1
and val2
as argumentsOne could instead have written the following equivalent code:
{
auto obj = myclass<SomeType>{}; // initialize object
x = obj(val1, val2); // invoke operator()
}
This is useful, for example, if you want to calculate the hash of an object using std::hash
but don't want an instance of std::hash
to live for a long time.
Upvotes: 6