Search code examples
c++objectconstructorstdtype-parameter

What is the meaning of this syntax std::class<>{}(arg1, arg2) in C++?


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?


Solution

  • 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:

    1. It create a temporary object of type myclass<SomeType> by calling the default constructor due to the uniform initializer {}.
    2. It then calls operator() on that temporary object, in this case supplying val1 and val2 as arguments
    3. The whole expression returns the result of the function call operator and the temporary is destroyed

    One 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.