自动推断模板中的函数类型
Auto deduce type of function in template
我有简单的map
实现和简单的id
(身份(:
template <typename T>
T map(const T& x, std::function<decltype(x[0])(decltype(x[0]))> f) {
T res(x.size());
auto res_iter = begin(res);
for (auto i(begin(x)); i < end(x); ++i) {
*res_iter++ = f(*i);
}
return res;
}
template <typename T>
T id(T& x) {return x;}
当我打电话时是
vector<int> a = {1,2,3,4,5,6,7,8,9};
map(a, id<const int>);
它可以工作,但我想在没有类型规范的情况下调用它,如下所示:
map(a, id);
当我这样做时,我得到错误:
error: cannot resolve overloaded function 'id' based on conversion to type 'std::function<const int&(const int&)>'
map(a, id);
^
如何解决它,为什么当错误包含正确的有界类型时,编译器无法从map
的上下文中推断出id
的类型?
如果您处于符合 C++14 的环境中,则有一种非常干净的方法可以执行此操作。不要使用 std::function 和模板化类,而是使用不受约束的转发引用和通用 lambda,如下所示:
#include <vector>
template <typename T,typename F>
T map(const T& x, F &&f) {
T res(x.size());
auto res_iter = begin(res);
for (auto i(begin(x)); i < end(x); ++i) {
*res_iter++ = f(*i);
}
return res;
}
auto id = [](auto x) { return x;};
int main()
{
std::vector<int> v = {1, 2, 3, 4};
auto v2 = map(v, id);
}
在 C++11 中,您必须将通用 lambda 替换为其 operator(( 是模板化方法的函子,如下所示:
struct {
template<typename T>
T operator()(T x) const
{
return x;
}
} id;
在 C++98 语法中,您将无法使用转发引用,因此您必须考虑复制和函子可变性问题。
这是因为id
不是一个函数。这是一个函数模板!
这意味着id
是一个生成函数(如id<const int>
(的模板,但本身并不是一个真正的函数。
运行时没有id
,只有id
创建的函数实例。
相关文章:
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 是否有任何建议来统一函数类型限定符并简化可恶的函数类型?
- 关于 C++ 中的函数类型定义
- 用于检测函数类型是否为否的特征
- 函数类型参数的模板参数推导
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++无效的函数类型转换
- STL 函数和函数类型与函数指针类型
- 如何将result_of与函数类型定义一起使用
- 将模板(没有规范)传递给 std::thread() 会出现错误:<未解析的重载函数类型>匹配错误
- C++ 编译错误:gnu_printf是无法识别的格式函数类型
- 专门用于"direct"函数类型(与函数指针类型相对)
- 将函数类型作为模板参数传递不会编译
- 通过参数传递 lambda(无函数类型模板)
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么比较函数类型需要指定为模板参数?
- 带有限定符的函数类型定义用例
- 如何声明对函数类型的常量引用
- 非类型模板参数允许各种函数类型?