A
aaragon
Hi everyone,
I'm trying to create two simple template classes where one of them
depends on the other to initialize its member integer variable. After
some time, I decided to post a message here because I don't really
understand why I can't make this work.
template<int n>
class ClassA
{
public:
int n_;
ClassA() : n_(n)
{}
};
template<class ClassA>
class ClassB
{
public:
int m_;
ClassB() : m_(ClassA::n_)
{}
};
int main()
{
typedef ClassA<2> ca;
typedef ClassB<ca> cb;
cb cb1;
return 1;
}
The compiler errors that I get:
aaragon@aaragon-laptop:~/Desktop$ g++ test.cxx
test.cxx: In constructor 'ClassB<ClassA>::ClassB() [with ClassA =
ClassA<2>]':
test.cxx:28: instantiated from here
test.cxx:5: error: object missing in reference to 'ClassA<2>::n_'
test.cxx:17: error: from this location
I guess that the error lies on the fact that a typedef is not an
instantiation of the object so therefore I cannot call the variable n
within ClassA. On the other hand, I cannot instantiate ClassA to
create the type definition of classB because I receive a compiler
error that tells me that the instantiated object of ClassA cannot
appear in a constant expression.
Is there a way around this? Maybe the solution is real simple. Thank
you.
I'm trying to create two simple template classes where one of them
depends on the other to initialize its member integer variable. After
some time, I decided to post a message here because I don't really
understand why I can't make this work.
template<int n>
class ClassA
{
public:
int n_;
ClassA() : n_(n)
{}
};
template<class ClassA>
class ClassB
{
public:
int m_;
ClassB() : m_(ClassA::n_)
{}
};
int main()
{
typedef ClassA<2> ca;
typedef ClassB<ca> cb;
cb cb1;
return 1;
}
The compiler errors that I get:
aaragon@aaragon-laptop:~/Desktop$ g++ test.cxx
test.cxx: In constructor 'ClassB<ClassA>::ClassB() [with ClassA =
ClassA<2>]':
test.cxx:28: instantiated from here
test.cxx:5: error: object missing in reference to 'ClassA<2>::n_'
test.cxx:17: error: from this location
I guess that the error lies on the fact that a typedef is not an
instantiation of the object so therefore I cannot call the variable n
within ClassA. On the other hand, I cannot instantiate ClassA to
create the type definition of classB because I receive a compiler
error that tells me that the instantiated object of ClassA cannot
appear in a constant expression.
Is there a way around this? Maybe the solution is real simple. Thank
you.