gpt4 book ai didi

c++ - 为什么这个重载函数的调用不明确?

转载 作者:太空狗 更新时间:2023-10-29 20:23:00 25 4
gpt4 key购买 nike

为什么这个构造函数调用不明确?

#include <functional>

class A {
std::function<int(void)> f_;
std::function<float(void)> g_;
public:
A(std::function<int(void)> f) { f_ = f; }
A(std::function<float(void)> g) { g_ = g; }
~A() {}
};

int main()
{
A a([](){ return (int)1; });
return 0;
}

注意类型转换。

有没有办法告诉编译器使用哪个构造函数重载?

最佳答案

这是标准中的一个缺陷。参见 DR 2132 :

Consider the following:

#include <functional>

void f(std::function<void()>) {}
void f(std::function<void(int)>) {}

int main() {
f([]{});
f([](int){});
}

The calls to f in main are ambiguous. Apparently because the conversion sequences to std::function from the lambdas are identical. The standard specifies that the function object given to std::function "shall be Callable (20.8.11.2) for argument types ArgTypes and return type R." It doesn't say that if this is not the case, the constructor isn't part of the overload set.

尝试使用函数指针作为参数:

A(int f()) { f_ = f; }
A(float g()) { g_ = g; }

关于c++ - 为什么这个重载函数的调用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280450/

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