c++ - 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);
}
解决方案
第二个版本,具有命名空间级别的功能,看起来非常实用:
[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 ~]$
因此,请检查您的第二个示例和错误消息。
推荐阅读
- r - 如何从 kableExtra kbl 表中删除 NA?
- sql-server - 使用 SQL 游标 SQL server 更新和设置
- hibernate - Spring Data JPA / Hibernate:在同一张表中使用JOIN列时如何避免不必要的JOIN
- javascript - 在数组中分组相同的值
- excel - 在 Excel VBA 中使用“不等于”运算符
- r - 删除具有R中其他列条件的重复行
- f# - 如何将双引号绑定到 F# 中的字符串?
- xpath - 是否有 XPATH 函数或运算符来比较节点的深度?
- alpine.js - Alpine 的脚本应该放在哪里?
- spring-boot - Teiid Springboot Starter 排序规则或语言环境