I want to create template function that would be able to extract any property of struct A.
Here is Source.h
struct B
{
int bbb;
};
struct C
{
double ccc;
};
struct A
{
B b;
C c;
};
template <class R>
auto foo(A* str, R getter) -> decltype(str->*getter);
Now I want use explicit instantiation approach for foo
Here comes Source.cpp:
#include "Source.h"
template <class R>
auto foo(A* str, R getter) -> decltype(str->*getter)
{
return str->*getter;
}
If we look at Main.cpp, we can see, that without explicit instantiation in the code block above we get link error:
//MAIN.cpp
#include "Source.h"
void main()
{
A a;
a.b.bbb = 7;
auto z = foo(&a, &A::b);
}
Now my question is how to explicitly instantiate foo for &A::b and &A::c types. I have tried tons of variants but nothing works. I am in visual studio 2015.
P.S. Oh, and one more. Can we make foo with default argument for
R = decltype(&A::b)
?
There you go:
template B &foo(A*, B A::*);
template C &foo(A*, C A::*);
As for the default argument, you need defaults for both the type and the value:
template <class R = B A::*>
auto foo(A* str, R getter = &A::b) -> decltype(str->*getter);