Function template with an operator

后端 未结 3 1609
花落未央
花落未央 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:07

    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.

    0 讨论(0)
  • 2020-12-05 05:13

    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.

    0 讨论(0)
  • 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 <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.

    0 讨论(0)
提交回复
热议问题