Reputation: 5255
I have theoretical question about templates in C++.
Let's say I have the following code:
struct C{
int val = 15;
};
struct B{
C c;
int k = 9;
};
struct A{
template<typename T, typename FType, FType T::* Field = nullptr>
void test(T& d){
if (Field != nullptr){
int a = d.*Field;
}
}
};
int main(int argc, char *argv[])
{
A a;
B be;
a.test<B, int, &B::c::val>(be);
//a.test<B, int, &B::k>(be);
}
The question is: why I can't access to B::c::val field, when I can access B::k?
B::c::val is also member of B. Or not?
Upvotes: 2
Views: 87
Reputation: 24606
B::c
is a member of B
, and C::val
is a member of C
, but there is nothing like B::c::val
What you are wanting to do here could be achieved like this:
struct A {
template<typename T, typename OType, typename IType, OType T::* OField = nullptr, IType OType::* IField = nullptr>
void test(T& d){
if (OField != nullptr && IField != nullptr) {
auto a = d.*OField.*IField;
}
}
};
int main(int argc, char *argv[])
{
A a;
B be;
a.test<B, C, int, &B::c, &C::val>(be);
}
http://coliru.stacked-crooked.com/a/f89b96274218e223
Of course, you could provide the member pointers as function parameters and let the compiler deduce the type parameters for you.
Upvotes: 1