简体   繁体   English

成员函数模板和C ++中的重载operator()

[英]Member-function templates and overloading operator() in C++

The following code snippet works for me: 以下代码段适用于我:

class Foo {
public:
    template <class T> T& get () { ... }
};

Foo foo;
foo.get<int>() = ...;

However, the following code snippet does not work for me: 但是,以下代码段对我不起作用:

class Foo {
public:
    template <class T> T& operator() () { ... }
};

Foo foo;
foo<int>() = ...;

The errors being: 错误是:

expected primary-expression before '>' token
expected primary expression before ')' token

Both errors refer to the foo<int>() 这两个错误都引用了foo<int>()

Why does this not work and is it possible to fix this? 为什么这不起作用,是否可以解决这个问题?

If you need to explicitly specify the template argument, you would need to use the operator syntax: 如果需要显式指定模板参数,则需要使用operator语法:

foo.operator()<int>()

There isn't any way to specify the arguments using the function-call syntax. 没有任何方法可以使用函数调用语法指定参数。 If you can't deduce the template arguments from the arguments to the function, it's better to use a member function than an operator overload. 如果无法从函数的参数中推导出模板参数,则最好使用成员函数而不是运算符重载。

The problem is that your template parameter list is in the wrong place; 问题是您的模板参数列表位置错误; it's as if you're trying to use an object or function called foo with template argument int , but in fact it's the operator() that you want the template parameter list on. 就好像你试图使用一个名为foo的对象或函数和模板参数int ,但实际上它是你想要模板参数列表的operator()

Unfortunately (arguably so, at least), there is no way around this with operators. 不幸的是(至少可以这么说),运营商无法解决这个问题。 You have to call them as full functions: 你必须把它们称为全功能:

class Foo {
public:
    template <class T> T& operator()() { ... }
};

Foo foo;
foo.operator()<int> = ...;

Hope this helps. 希望这可以帮助。

Alternatively you could do this 或者你可以这样做

class Foo {
public:
  template <class T> operator T&() { ... }
};

Then it will automatically call the right function depending on the "return" type: 然后它将根据“返回”类型自动调用正确的函数:

Foo foo;
int i=foo;

I know that most people don't like this as the function that's being called depends on the return type, but I find it a great "trick" that often cleans up syntax. 我知道大多数人不喜欢这个,因为被调用的函数取决于返回类型,但我发现它是一个很好的“技巧”,经常清理语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM