0

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) ?

Demaunt
  • 1,183
  • 2
  • 16
  • 26

1 Answers1

3

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);
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • Sorry but i still get link error from main i call auto z = foo(&a, &A::b); and error – Demaunt Jan 18 '18 at 17:36
  • @Demaunt [It works fine here](https://wandbox.org/permlink/7NJUNZSj1WOg7bWd). What exactly is the error? – Quentin Jan 18 '18 at 17:45
  • 1) Error LNK2019 unresolved external symbol "struct B & __cdecl foo(struct A *,struct B A::*)" (??$foo@PQA@@UB@@@@YAAAUB@@PAUA@@PQ1@U0@@Z) referenced in function _main ConsoleApplication2 ... 2) Warning C4667 'B &foo(A *,B A::* )': no function template defined that matches forced instantiation – Demaunt Jan 18 '18 at 17:50
  • perhaps another "feature" from Microsoft compiler, guess I am done with this feature, because the project I am working on depends on MVSC – Demaunt Jan 18 '18 at 17:51
  • @Demaunt that warning is extremely fishy (and should be a hard error as well). Have you made sure to put the explicit instantiations after the function's definition in `Source.cpp`? – Quentin Jan 18 '18 at 17:52
  • My code is EXACTLY the same as from wandbox (i even copy pasted it for all three files and still get the error) – Demaunt Jan 18 '18 at 17:57
  • @Demaunt this looks like [this MSVC bug related to `decltype`](https://connect.microsoft.com/VisualStudio/feedback/details/1349269/msvc-2015-cannot-instantiate-function-template-involving-decltype-new). The bad news is that it is still not fixed. – Quentin Jan 18 '18 at 18:08
  • well, at least I know how to explicitly instantiate decltyped functions using proper compliers. Thank you very much – Demaunt Jan 18 '18 at 18:09