2

クラスオブジェクトのテンプレート化された関数呼び出し演算子を暗黙的に呼び出すにはどうすればよいですか?

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

2 に答える 2

4

テンプレート引数を明示的に指定する必要がある場合は、できません。それを指定する唯一の方法は、最初の構文を使用することです。

テンプレート引数が関数引数から推測できる場合、またはデフォルトがある場合、その引数が必要な場合は単純な関数呼び出し構文を使用できます。

型の用途によっては、オブジェクトを宣言するときに引数を指定できるように、メンバーではなくクラスをテンプレートにすることが理にかなっている場合があります。

于 2014-11-11T17:20:44.937 に答える
0

仕方がありません。のような未使用のパラメーターで少しごまかすことが可能です

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

しかし、それはあなたが正確に望むものではありません。

于 2014-11-11T17:23:42.207 に答える