实例化重载的函数模板
Instantiate overloaded function template
我在使用std::cref
时遇到了这个问题。一个最小的例子如下:
template<typename Fn, typename T>
auto apply(Fn f, const T &t) -> decltype(f(t))
{
return f(t);
}
int n = 123;
apply(std::cref<int>, n); // <- compile error: can't infer type `Fn`
apply([](const int &x) { return std::cref(x); }, n); // ok
我认为第一个例子的问题是std::cref<T>
有两个重载版本,一个接受const T &
,另一个接受std::reference_wrapper<const T>
。在我的情况下,有可能实例化一个特定的版本吗?
在这种情况下,apply
函数似乎有点多余。为什么不裁掉中间人呢?
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
int main() {
std::vector<int> v(10);
std::vector<std::reference_wrapper<const int>> v2;
std::transform(v.begin(), v.end(), std::back_inserter(v2),
static_cast<std::reference_wrapper<const int>(*)(const int&)>(&std::cref<int>));
}
问题是cref
有几种形式。因此,当你写cref<int>
时,还不清楚你的意思是:
reference_wrapper<const int> cref (const int& elem)
reference_wrapper<const int> cref (reference_wrapper<int>& x)
lambda版本没有这种歧义。顺便说一句,习惯它是个好主意;-)
现在,如果可读性真的是一个问题,没有什么可以阻止你这样做:
auto take_ref = [](const int &x) { return std::cref(x); };
apply(take_ref, n); // compile fine
相关文章:
- 将重载的成员函数传递给函数模板
- 使用模板重载函数
- 基于 SFINAE 的特征实现问题与函数模板重载
- 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?
- 函数模板重载 - 部分专用化
- 函数模板重载差异
- 用另一个函数模板重载函数模板合法吗
- 带有指针参数的函数模板重载解析
- 依赖类型不明确的 c++11 可变参数函数模板重载是否不明确
- 函数模板重载 - 专用化
- 函数模板重载 clang++
- 函数模板重载难题
- C++函数模板重载
- 继承和成员函数模板重载
- 全局函数模板重载和const形参
- 使用const引用解析函数模板重载
- 函数模板重载解析
- 为派生的可变参数类模板调用函数模板重载
- Clang 和 GCC 在解决可变参数函数模板重载时的行为不同
- 函数模板重载分辨率混淆