I'm trying to detect when an explicit constructor call has been called vs. an implicit one.
Suppose we have a class Foo
:
class Foo{
public:
Foo(int _val) : val(_val){};
private:
int val;
}
void bar(Foo f){
...
}
We can call bar like:
Foo f(10);
bar(f);
or like:
bar(10); // implicit initialization
Now, I am aware that if we make the ctor explicit:
class Foo{
public:
explicit Foo(int _val) : val(_val){};
private:
int val;
}
Then we can get this error:
bar(10); // ERROR! implicit initialization not allowed.
So I thought perhaps there could be a workaround to detect an explicit call vs. implicit, like this:
class Foo{
public:
explicit Foo(int _val) : val(_val){}; // calling Foo f(10); bar(f);
Foo(int _val) : val(_val){}; // calling bar(10);
private:
int val;
}
But as expected, it returns "cannot be overloaded", as the function signatures are ambiguous.
The end result should be something like:
class Foo{
public:
explicit Foo(int _val) : val(_val), flag(true) {}; // calling Foo f(10); bar(f);
Foo(int _val) : val(_val), flag(false) {}; // calling bar(10);
private:
int val;
bool flag;
}
void bar(Foo f){
std::cout << "f's flag set to : " << f.flag << std::endl;
}
Foo f(10);
bar(f); // f's flag set to : 1
bar(10); // f's flag set to : 0
But obviously since the above attempt was futile, and I don't have a better idea, I was wondering if it is even possible to do this in C++. If it's not, then it's fine.
No, it's not possible. If this is purely out of curiosity, then you have your answer. If there is a real problem you are trying overcome, you may want to post the real problem.