template<> operator()

P

Phil Endecott

Dear Experts,

I find myself wanting to write

class functor {
template <typename T>
T operator()(args) {...}
};

in order to

functor f;
sometype r = f<sometype>(3.14);


but I can't get anything to work. Is operator() allowed to be a
template function? (Maybe I am, because I only get errors at the point
where I try to use it.) If it is allowed, how am I supposed to call it?

Thanks for any clarification,

Phil.
 
B

Barry

Phil said:
Dear Experts,

I find myself wanting to write

class functor {
template <typename T>
T operator()(args) {...}
};

in order to

functor f;
sometype r = f<sometype>(3.14);

sometype r = f.operator()<sometype>(3.14);

when you don't have templated argument list for template operator to
implicit instantiate. I suggest you write ordinary function rather than
operator().
 
V

Victor Bazarov

Phil said:
Dear Experts,

I find myself wanting to write

class functor {
template <typename T>
T operator()(args) {...}
};

in order to

functor f;
sometype r = f<sometype>(3.14);


but I can't get anything to work. Is operator() allowed to be a
template function? (Maybe I am, because I only get errors at the
point where I try to use it.) If it is allowed, how am I supposed to
call it?

It's allowed to be a template, but, like a constructor, the type has
to be deducible from the arguments. For the function call operator
the syntax is rather ugly

sometype r = f.operator()<sometype>(3.14);

so you probably don't want to use it. And there is no syntax at all
for templated constructors.

Now, since the syntax you want to use is unavailable, you're better off
defining a named function instead of the operator(). Then you call it

sometype r = f.funcname<sometype>(3.14);

As to availability of the syntax, you might want to ask in comp.std.c++
about the rationale behind disallowing it. My guess would be that the
presence of the less-than operator after the name of an object is
already reserved for comparison purposes. IOW

sometype r = f < ...

means you're comparing 'f' to the rest of the expression. It most
likely would be difficult to allow you to have a template argument list
after the object name in a rare case you've defined a function call
operator as a template.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top