gpt4 book ai didi

c++ - 推断函数指针的模板参数

转载 作者:行者123 更新时间:2023-12-02 16:22:51 25 4
gpt4 key购买 nike

对于下面的代码:

#include <iostream>
#include <vector>

template <class T>
inline auto foo(const T* A)
{
return A[0];
}

template <class T>
struct impl
{
template <typename F>
static auto bar(const T& A, F func)
{
return func(&A[0]);
}
};

int main()
{
std::vector<size_t> A = {2, 3, 4};
std::cout << impl<decltype(A)>::bar(A, &foo) << std::endl;
return 0;
}

我得到(使用 C++14 在 macOS 上使用 clang)

main.cpp:23:18: error: no matching function for call to 'bar'
std::cout << impl<decltype(A)>::bar(A, &foo) << std::endl;
^~~~~~~~~~~~~~~~~~~~~~
main.cpp:14:17: note: candidate template ignored: couldn't infer template argument 'F'
static auto bar(const T& A, F func)
^
1 error generated.

我的问题是:为什么?我该如何解决?

最佳答案

foo 是模板的名称,而不是函数的名称。 bar 需要类型,而不是模板。幸运的是,lambda 表达式是一种将泛型函数包装到已知对象类型中并为您进行调度的快速简便方法。那会给你

std::cout << impl<decltype(A)>::bar(A, [](const auto& var){ return foo(var); }) 
<< std::endl;

关于c++ - 推断函数指针的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65183976/

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