How to access non-static class member?
class A
{
int value_ = 0;//I want to access this member in class inheriting from A
};
template<class X = A>
class Y :X
{
static_assert(value_ == 0,"Non-zero not allowed");//here I want to access value_ from X which is A by default. Is this possible?
};
What you are specifically doing is not possible, for several reasons.
First,
static_assertrequires it’s argument to be a compile-time constant expression.value_is most assuredly not.You could try to make it a constant expression by labeling it
constexpr. But C++11 doesn’t allowconstexprfor non-static data members. And even if it did, that’s not going to help becausevalue_is a non-static member. As such, it doesn’t exist yet. It only exists when there is an actual class instance, something that has athispointer. Yourstatic_assertexpression doesn’t create one of those objects, so there’s no way to access it.Therefore, in order to make this “work” (to the extent that “working” does something meaningful), you must:
Aaconstexprconstructor, so that you can create aconstexprinstantiation of it.static_assertmust actually create a type using theconstexprconstructor and access the data member in question.Now, if you do this, you’re going to find that it doesn’t give you what you want (based on this statement, since your question didn’t explain what exactly it is you’re trying to accomplish):
Note that
static_assertis static. Whereas “every time object of this class is created” is a runtime event. You cannot perform a static test on something that happens at runtime.What you want is regular
assert, notstatic_assert.