Compilation issue with instantiation pattern

Consider the following code:

#include <iostream>

struct S {
  void f(const char* s) {
    std::cout << s << '\n';
  }
};

template <typename... Args, void(S::*mem_fn)(Args...)>
void invoke(S* pd, Args... args) {
  (pd->*mem_fn)(args...);
}

int main() {
  S s;
  void(*pfn)(S*, const char*) = invoke<const char*, &S::f>;
  pfn(&s, "hello");
}

When compiling the code, clang gives the following error:

main.cpp:16:33: error: address of overloaded function 'invoke' does not match required type 'void (S *, const char *)'
  void(*pfn)(S*, const char*) = invoke<const char*, &S::f>
                                ^~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:10:6: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'Args'
void invoke(S* pd, Args... args) {
     ^
1 error generated.

The message seems to suggest that the template instance invoke<const char*, &S::f>failed. Can someone give me some clues as to why this is? I believe this has something to do with the parameter package.

+4
source share
2 answers

Your code is poorly formed. mem_fnis in an untrackable context according to [temp.deduct.type]:

:
  -...
  - , -.

[temp.param]:

, - (14.8.2). [:

template<class T1 = int, class T2> class B; // error

// U can be neither deduced from the parameter-type-list nor specified
template<class... T, class... U> void f() { } // error
template<class... T, class U> void g() { } // error

-end ]

mem_fn :

template <typename... Args, void(S::*mem_fn)(Args...)>
void invoke(S* pd, Args... args) {

. . :

template <typename... Args>
void invoke(S* pd, void(S::*mem_fn)(Args...), Args... args);

, :

template <typename... Args>
struct Invoke {
    template <void (S::*mem_fn)(Args...)>
    static void invoke(S* pd, Args... args);
};

void(*pfn)(S*, const char*) = Invoke<const char*>::invoke<&S::f>;
+5

Barry decltype -, , :

template <typename Sig, Sig Fn>
struct invoke;

template <typename Ret, class Class, typename... Args, Ret(Class::*mem_fn)(Args...)>
struct invoke <Ret(Class::*)(Args...), mem_fn>
{
    static void exec (Class* pd, Args... args)
    {
        (pd->*mem_fn)(args...);
    }
};

:

void(*pfn)(S*, const char*) = invoke<decltype(&S::f),&S::f>::exec;
+2

All Articles