Function template with an operator

31,786

Solution 1

You need to specify T.

int i = c.operator()<int>();

Unfortunately, you can't use the function call syntax directly in this case.

Edit: Oh, and you're missing public: at the beginning of the class definition.

Solution 2

You're basically right. It is legal to define templated operators, but they can't be called directly with explicit template arguments.

If you have this operator:

template <typename T>
T operator()();

as in your example, it can only be called like this:

int i = c.operator()<int>();

Of course, if the template argument could be deduced from the arguments, you could still call it the normal way:

template <typename T>
T operator()(T value);

c(42); // would call operator()<int>

An alternative could be to make the argument a reference, and store the output there, instead of returning it:

template <typename T>
void operator()(T& value);

So instead of this:

int r = c.operator()<int>();

you could do

int r;
c(r);

Or perhaps you should just define a simple get<T>() function instead of using the operator.

Solution 3

Aren't you thinking of

class Foo {
    public:
    template<typename T>
    operator T() const { return T(42); }
};

Foo foo;

int i = (int) foo; // less evil: static_cast<int>(foo);

live example. This proves you do not need to specify the template argument, despite the claim in the accepted answer.

Share:
31,786
pr3sidentspence
Author by

pr3sidentspence

Chrome WebGL implementor

Updated on March 16, 2020

Comments

  • pr3sidentspence
    pr3sidentspence about 4 years

    In C++, can you have a templated operator on a class? Like so:

    class MyClass {
    public:
        template<class T>
        T operator()() { /* return some T */ };
    }
    

    This actually seems to compile just fine, but the confusion comes in how one would use it:

    MyClass c;
    int i = c<int>(); // This doesn't work
    int i = (int)c(); // Neither does this*
    

    The fact that it compiles at all suggests to me that it's doable, I'm just at a loss for how to use it! Any suggestions, or is this method of use a non-starter?