Is it possible to explicitly specify template arguments for the operator?

I have a Foo class:

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

T cannot be deduced, but I want you to be able to say something like

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

But this is a syntax error.

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

+4
source share
2 answers

You can do this using the operator name syntax:

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

This, of course, is ugly. There are two solutions:

  • Modify the operator so that it accepts a parameter, and therefore the type is inferred.

  • Change it from a statement to a named function. In any case, this does not seem to be a typical use for operator().

+4
source

Here is an example that compiles and runs:

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

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

. -. . , .

+2

Source: https://habr.com/ru/post/1531822/


All Articles