Member patterns and operator overloading () 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 fragment does not work for me:

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

Errors:

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

Both errors relate to foo<int>()

Why does this not work, and can it be fixed?

+6
c ++ operator-overloading templates
source share
3 answers

If you need to explicitly specify a template argument, you will need to use the operator syntax:

 foo.operator()<int>() 

Cannot specify arguments using call function syntax. If you cannot derive template arguments from function arguments, it is better to use a member function than operator overloading.

+10
source share

The problem is that the list of options for your template is in the wrong place; as if you are trying to use an object or function named foo with an int template argument, but actually it is operator() in which you want to include a list of template parameters.

Unfortunately (perhaps so, at least), there is no way around this with operators. You should call them full functions:

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

Hope this helps.

+1
source share

Alternatively you can do this

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

Then it will automatically select the desired function depending on the type of "return":

 Foo foo; int i=foo; 

I know that most people do not like this, because the function being called depends on the type of return, but I think this is a great "trick" that often clears the syntax.

-one
source share

All Articles