I want to understand how typecast-overloading works. For my question, I want to know
- The thing I'm trying to do is it possible?
- If yes, then how?
I want the user to be able to pass a vector<float>
to a function. This function is implemented in such a way that its parameter is a wrapper class around vector<float>
.
Can typecast-overloading help in such a case? (automatically convert vector<float>
into Layer
)
or do we have to use some complicated templated function?
// ---------- someFile.cpp ------------
class Layer {
vector<float> l;
public:
friend void process (const Layer& someLayer);
}
// ---------- main.cpp ------------
int main() {
vector<float> vec = {1.0, 1.5, 2.0};
process(vec);
}
CodePudding user response:
All that's needed is a non-explicit constructor taking the correct argument (a so-called conversion constructor):
class Layer {
vector<float> l;
public:
Layer(vector<float> const& v);
};
Now the compiler will be able to do implicit conversions from vector<float>
to Layer
.
Note that it's usually not recommended to have such conversion constructors being non-explicit (not declared using the explicit
keyword), because sometimes implicit conversions might be unexpected and not wanted.