I am developing quite a large Class whose objects require relatively costly validation if they are created by the public constructors, but for which the validation can be dispensed with for private constructors (since one can assume to be working with already-validated data).
In C++, is it possible to overload an operator (e.g. add or +) with the same signature in such a way that a different version of it is called from 'outside' the class (with input validation) and a different version is called from a member function (without the validation)?
For example, I'd like something like this:
class cBigClass { ... public: friend cBigClass operator*(const int a, const cBigClass& C) { this->Validate(a); cBigClass B = this->ComplicatedFunctionActuallyImplementingMultiply(a, C); return B; } private: friend cBigClass operator*(const int a, const cBigClass& C) { cBigClass B = this->ComplicatedFunctionActuallyImplementingMultiply(a, C); return B; } private: void DoSomethingPrivately() { int a = 1; cBigClass C, D; D = a*C; // Calls 'private' version of * without validation } }; ... // Elsewhere, e.g. in main() int a = 2; cBigClass A, B; A = a*B; // Calls 'public' version of * with validation A naive re-definition obviously throws a compiler error (g++), even when one is made public and one private. Both versions of such a function essentially have to have the same signature - is there a trick / hack for something like this? I would really like to avoid re-defining the operator code since it would lead to a lot of duplication.
D = a*C;andA = a*B;are doing the same thing/operation. So distinguishing between the two based on where they occur is just not possible.a = b * Cbecomes something likea.operator=(b.operator*(C))) is the same, regardless of where the expression occurs. Access control (e.g. to prevent calling aprivatefunction by a non-member/non-friend) occurs after that. The usual approach would be to provideprivatefunctions that can be called directly by a class's member functions (or friends) and provide a set ofpublicfunctions which (optionally) do validation and call theprivatefunctions.private)friend cBigClass operator*(ValidatedInt, const cBigClass&). (Similar togsl::not_null).