首页 > 解决方案 > C++ - 为什么这个带有函数指针参数的候选模板会被忽略?

问题描述

我有一个头文件,其中包含这样的方法(及其声明):

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);
    }
}

后来我像这样使用它:

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

但是,在尝试构建此代码时,出现以下错误:

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

此外,这也不起作用:

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

它会导致相同的错误。

我觉得我遗漏了一些明显的东西,但是从我看过的所有其他代码示例/ SO 问题来看,这些看起来都没有错。为什么候选模板被忽略?为什么我的论点GetT无效?

编辑:这是一个完整的、可验证的代码示例:

#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);
}

这是它在网上编译的图片: 在此处输入图像描述

标签: c++templatesfunction-pointers

解决方案


第二个版本,具有命名空间级别的功能,看起来非常实用:

[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 ~]$ 

因此,请检查您的第二个示例和错误消息。


推荐阅读