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>() = ...;
开发者_JS百科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>()
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:
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.
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.
精彩评论