简体   繁体   中英

C++ - Why is this candidate template with a function pointer parameter ignored?

I have a header file including a method (and it's declaration) like this:

template<typename T, unsigned int N, T (*GetT)(int)>
void foo(std::vector<T> &out) {
    out.clear();
    for (int i = 0; i < N; i++) {
        T t = GetT(i);
        out.push_back(t);
    }
}

and later on I use it like this:

std::vector<double> my_vec;
std::function<double(int)> get_double = [](int i) -> double { return ... };
my_obj.foo<double, 5, &get_double>(my_vec);

However, upon attempting to build this code I'm presented with the following error:

error: no matching member function for call to `foo`
note: candidate template ignored: invalid explicitly-specified argument for template parameter `GetT`

Additionally, this doesn't work either:

double get_double(int i) { return ... }

std::vector<double> my_vec;
double (*get_double_ptr)(int);
get_double_ptr = &get_double;
my_obj.<double, 5, &get_double>(my_vec);

It results in the same error.

I feel like I'm missing something obvious, but from all other code examples/SO questions I've looked at none of this looks wrong. Why is the candidate template being ignored? Why is my argument for GetT invalid?

Edit: Here is a complete, verifiable code example:

#include <vector>
template<typename T, unsigned int N, T (*GetT)(int)>
void foo(std::vector<T> &out) {
    out.clear();
    for (int i = 0; i < N; i++) {
        T t = GetT(i);
        out.push_back(t);
    }
}

double get_double(int n) {
    return n * 1.5d;
}

int main(int argc, char **argv) {
   std::vector<double> my_vec;
   foo<double, 5, &get_double>(my_vec);
}

Here's a picture of it compiling online: 在此处输入图片说明

The second version, with a namespace-level function, looks quite functional:

[bipll@home ~]$ cat wat.cpp 
#include <vector>

struct Nyan {
    template<typename T, unsigned int N, T (*GetT)(int)> void foo(std::vector<T> &&out) {}
};

double getDouble(int) { return 3.1416; }

int main() {
    Nyan n;
    n.foo<double, 42, &getDouble>({});
}
[bipll@home ~]$ g++ wat.cpp 
[bipll@home ~]$ ./a.out 
[bipll@home ~]$ 

So check your second example and error messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM