Function template with an operator

后端 未结 3 1630
花落未央
花落未央 2020-12-05 04:43

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

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


        
3条回答
  •  孤街浪徒
    2020-12-05 05:20

    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 
    T operator()();
    

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

    int i = c.operator()();
    

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

    template 
    T operator()(T value);
    
    c(42); // would call operator()
    

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

    template 
    void operator()(T& value);
    

    So instead of this:

    int r = c.operator()();
    

    you could do

    int r;
    c(r);
    

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

提交回复
热议问题