'function call operator in class or method?
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
Solution 1:[1]
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 of passing a std::vector<foo::bar> as shown below:
//--------vvvvvvvvvvvvvvvvvvvvv----------> expects std::vector<foo::bar>
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);
}
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.
Solution 2:[2]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Silvio Mayolo |
