如何隐式调用函数调用运算符

How to Implicitly Call a Function Call Operator?

本文关键字:运算符 函数调用 调用 何隐式      更新时间:2023-10-16

如何隐式调用类对象的模板化函数调用运算符?

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的输出错误为:

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

如果需要显式指定模板参数,则不能。指定它的唯一方法是使用第一个语法。

如果模板参数可以从函数参数推导出来,或者有默认值,那么如果需要该参数,可以使用简单的函数调用语法。

根据类型的用途,使类(而不是成员)成为模板可能是有意义的,因此您可以在声明对象时指定参数。

没有办法。使用像这样未使用的参数可以作弊

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

但这并不是你想要的。