sometimes (quite rarely) I need to get protected members from existing variables
like this:
struct S {
protected:
int i;
};
struct T : S {
using S::i;
};
int main() {
S s;
static_cast<T&>(s).i = 0;
}
I’m almost sure this ( static_cast(s) ) is UB, but is someone know what the C++ standard (2003) says about this situation?
This type of operation is actually the basis for implementing the constant reoccurring template pattern, where inside the base-class you actually
static_castthethispointer of the base-class to the derived-class template type. SinceSis an unambiguous base class ofT, and you are not accessing any members from thestatic_castthat are not already members ofS, I don’t see why you would encounter any issues.Section 5.2.8 on static casting in paragraph 5 states:
You seem to be meeting all the requirements that avoid undefined behavior. That is:
Tis derived fromSStoTdoes exist sinceSis both accessible and an unambiguous base-class ofT(requirements from 4.10)Sis not a virtual base-class ofT