I want my class template A to be able to have a member, that is only defined in B, while B inherits A.
Here is the code that would theoretically work, but doesn't compile.
template< typename T >
class A
{
public:
typename T::member mSomething;
};
class B : public A< B >
{
public:
struct member
{
int val;
};
};
int main( int argc, char** argv )
{
B* b = new B;
A<B>* a = b;
b->mSomething.val = 5;
if( a->mSomething.val == 5 )
{
std::cout << "doing good";
}
return 0;
}
This code does not compile on MSVCP 2010 with the error" 'member' : is not a member of 'B' "
How could I get around this?
CRTP base classes can't access types defined in the derived class. When A<B>
is instantiated, B
is an incomplete type and has no members, so you can't access the contents.
You must define the type outside B
.
For anyone wondering, this is the solution that I ended up using:
// Base class in file 1
template< typename T, typename TT >
struct A
{
TT foo;
};
// derived in file 2, one class for the member outside the definition
// and one main class.
struct C
{
int val;
};
struct B : public A< B, C >
{
};
// Usage from wherever you please.
int main( int argc, char** argv )
{
B* b = new B;
A<B, C>* a = b;
b->foo.val = 5;
if( a->foo.val == 5 )
{
std::cout << "doing good";
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.