gpt4 book ai didi

c++ - 自动扣除失败并显示消息 "inconsistent deduction for auto return type"

转载 作者:行者123 更新时间:2023-12-01 14:35:10 27 4
gpt4 key购买 nike

我写了下面的测试:

#include <cassert>
#include <iostream>
#include <string>
#include <cmath>
#include <functional>

// Works with std::function !
//std::function<double(double)> set_unary_operation(const std::string& unary)
auto set_unary_operation(const std::string& unary)
{
if(unary == "EXP")
return [](const double& x){ return std::exp(x);};
if(unary == "LOG")
return [](const double& x){ return std::log10(x);};
if(unary == "_LN")
return [](const double& x){ return std::log(x);};
if(unary == "ABS")
return [](const double& x){ return std::abs(x);};

return [](const double& x){return x;};

}

bool is_equal(double&& value, double&& test)
{
double epsilon = 0.0000001;
return (value-epsilon < test) && (value+epsilon > test);
}

int main()
{
// TEST OPERATOR --------------------------------------------------------------------------
{
std::string in = "EXP";

auto f = set_unary_operation(in);

std::cout << "f = EXP ; f(1) = "<< f(1) << "; f(2.5) = " << f(2.5) << std::endl;

assert(is_equal(f(1) , 2.71828182));
assert(is_equal(f(2.5), 12.1824939607));
}

return 0;
}

如果我定义 set_unary_operation 的返回类型,代码工作正常作为std::function<double(double)> ,但是当我使用 auto 并显示以下消息时失败了:

error: inconsistent deduction for auto return type: ‘moteur_de_calcul::set_unary_operation(const string&)::<lambda(const double&)>’ and then ‘moteur_de_calcul::set_unary_operation(const string&)::<lambda(const double&)>’

我试图理解推导失败的原因(示例可以在这里找到:https://onlinegdb.com/Sk7bitBxD)。

最佳答案

每个lambda expression产生独特的闭包类型,

The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression.

导致return type deduction失败,因为它们不是同一类型。

If there are multiple return statements, they must all deduce to the same type

正如您所说,您可以将 std::function 指定为返回类型。

关于c++ - 自动扣除失败并显示消息 "inconsistent deduction for auto return type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63031426/

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