gpt4 book ai didi

c++ - 实例化重载函数模板

转载 作者:搜寻专家 更新时间:2023-10-31 01:35:35 25 4
gpt4 key购买 nike

我在使用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>));
}

关于c++ - 实例化重载函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37057265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com