Search code examples
c++templatesfunction-call-operator

How to Implicitly Call a Function Call Operator?


How does one implicitly call a class object's templated function call operator?

class User_Type
{
public:
    template< typename T > T operator()() const;
};

void function()
{
    User_Type user_var;
    int int_var_0 = user_var.operator()< int >(); // explicit function call operator; ugly.
    int int_var_1 = user_var< int >(); // implicit function call operator.
}

g++-4.9 -Wall -Wextra's output error is:

    error: expected primary-expression before ‘int’
        auto int_var_1 = user_var< int >();
                                   ^

Solution

  • If the template argument needs to be specified explicitly, then you can't. The only way to specify it is to use your first syntax.

    If the template argument can be deduced from the function arguments, or has a default, then you can use simple function-call syntax if you want that argument.

    Depending on what the type is used for, it might make sense to make the class, rather than the member, a template, so you can specify the argument when declaring the object.