Charles L Wilcox
Charles L Wilcox

Reputation: 1124

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 >();
                                   ^

Upvotes: 2

Views: 742

Answers (2)

dev_null
dev_null

Reputation: 1997

There is just no way. it's possible to cheat a bit with a non-used parameter like

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

void function()
{
    User_Type user_var;
    int int_var_1 = user_var((int*)0); // implicit function call operator.
}

but it will not be what you precisely want.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254431

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.

Upvotes: 4

Related Questions