Home > Blockchain >  function call operator in class or method?
function call operator in class or method?

Time:03-22

class foo
{
public:
    struct bar
    {
        bar() {}
        int bar_var;
    };

    operator std::vector<bar>() {
        return m_list;
    }

private:
    std::vector<bar> m_list;
    int foo_var;
};

Here defined a class foo, what is the semantic "operator std:vector<bar>()" mean here? I don't think it is an overloaded function call operator.

Compile with the above code works OK

CodePudding user response:

what is the semantic "operator std:vector()" mean here?

It denotes a conversion operator that allows you to use a foo object where a std::vector<bar> is expected. A conversion operator is a special kind of member function that converts a value of a class type to a value of some other type.

For example, say we have a function called func that takes a std::vector<foo::bar> as its only parameter. Now, you can even call this function by passing a foo object instead passing a std::vector<foo::bar> as shown below:

//a function that takes a vector<bar> as parameter 
void func(std::vector<foo::bar> m)
{
    std::cout<<"func called"<<std::endl;
}
int main()
{
    foo fObject;
//-------vvvvvvv---->passing a foo object which implicitly uses the conversion operator    
    func(fObject); 
    
}

Working demo

In the above demo, func expects a std::vector<foo::bar>. But we're passing fObject which is an object of type foo and so there will be an implicit conversion of fObject to std::vector<foo::bar> using the conversion operator that you provided.

CodePudding user response:

It's a conversion function. In your example, a foo will happily call that function if it's ever used in a context where a std::vector<bar> is expected. A more typical use case might look something like

class MyCustomNumberType {
private:
  // Super secret number arithmetic stuff.
public:
  operator double() {
    // Convert to a double and return here...
  }
}

MyCustomNumberType foo = /* more complicated math ... */;
double bar = foo   1.0;
  • Related