fumigail
fumigail

Reputation: 853

Can I explicitly specify template arguments for an operator?

I have the class Foo:

class Foo {
    template <typename T>
    T* operator () (void) {
        return (T*) something;
    }
}

T can't be deduced, but what I want is to be able to say something like

Foo foo;    
type_t bar = foo <type_t> ();

But this is a syntax error.

Is there a way to do this? (or perhaps some better way to pass in a type without providing an instance of the type?)

Upvotes: 9

Views: 1203

Answers (2)

You can do it using the operator name syntax:

type_t *bar = foo.operator() <type_t> ();

That's of course ugly. There are two solutions:

  1. Change the operator so that it takes a parameter and thus the type is deducible.

  2. Change it from an operator to a named function. It doesn't seem like a typical use for operator() anyway.

Upvotes: 8

Christian Hackl
Christian Hackl

Reputation: 27528

Here's an example which compiles and runs:

struct Foo {
    template <typename T>
    T* operator () () {
        return (T*) 0;
    }
};

int main()
{
    double* bar = Foo().operator()<double>();
}

But that's really ugly. It is a clear case of operator-overloading abuse. Consider using an ordinary function name. Operator overloading should make code faster to read, not the opposite.

Upvotes: 2

Related Questions