Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation issue with instantiating function template

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 instantiation invoke<const char*, &S::f> has failed. Could somebody give me some clues as to why is this? I believe it has something to do with the parameter pack.

like image 704
Lingxi Avatar asked Mar 16 '23 06:03

Lingxi


1 Answers

Your code is ill-formed. mem_fn is in a non-deduced context according to [temp.deduct.type]:

The non-deduced contexts are:
— ...
— A function parameter pack that does not occur at the end of the parameter-declaration-list.

And from [temp.param]:

A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list of the function template or has a default argument (14.8.2). [ Example:

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 example ]

The mem_fn argument in this declaration:

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

follows a template parameter pack. It cannot be deduced from the list. You could, however, pass it as an argument:

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

Or wrap the whole thing in a struct so that you don't need to follow a parameter pack with another template:

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>;
like image 170
Barry Avatar answered Mar 19 '23 14:03

Barry