gpt4 book ai didi

c++ - 从 std::function 调用签名中推导出模板参数

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:18 24 4
gpt4 key购买 nike

考虑这个模板函数:

template<typename ReturnT>
ReturnT foo(const std::function<ReturnT ()>& fun)
{
return fun();
}

为什么编译器无法从传递的调用签名中推断出 ReturnT

bool bar() { /* ... */ }

foo<bool>(bar); // works
foo(bar); // error: no matching function call

最佳答案

bool (*)() 类型的函数指针可以转换为std::function<bool()>但不是同一类型,因此需要进行转换。在编译器检查该转换是否可行之前,它需要推断出 ReturnT作为bool ,但要做到这一点,它需要已经知道 std::function<bool()>是一种可能的转换,在推导出 ReturnT 之前是不可能的...看到问题了吗?

另外,请考虑 bool(*)()也可以转换为 std::function<void()>std::function<int()> ...应该推断出哪个?

考虑这种简化:

template<typename T>
struct function
{
template<typename U>
function(U) { }
};

template<typename T>
void foo(function<T>)
{ }

int main()
{
foo(1);
}

编译器怎么知道你是否想创建function<int>function<char>function<void>当它们都可以从 int 构建时?

关于c++ - 从 std::function 调用签名中推导出模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30961834/

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