简体   繁体   English

Scala和C ++ 11的类型推断有什么区别?

[英]What are the differences between the type inference of Scala and C++11?

I'm curious what the differences between the type inference of Scala and C++11 are. 我很好奇Scala和C ++ 11的类型推断之间的区别是什么。 In which situations do I have to specify the types in one language but not in the other? 在哪种情况下,我必须用一种语言指定类型而不是另一种语言? One difference seems to be the return type of functions which always have to be specified in C++11, although decltype and the new function syntax with a trailing return type allow to specify a inferred type. 一个区别似乎是函数的返回类型总是必须在C ++ 11中指定,尽管decltype和具有尾随返回类型的新函数语法允许指定推断类型。

C++ cannot infer such anonymous functions: C ++无法推断出这样的匿名函数:

// this wont work*
void somefunc(std::vector<int>& v) 
{
    std::for_each(v.begin(), v.end(), [](auto &x) { x++; });
}
//                                        /\
//                                         ------ I want this to be infered

whereas Scala can: 而斯卡拉可以:

def somefunc(v: Vector[Int]) = v.map(x => x +1)

* not sure that I've dealt correctly with C++ code syntax, I don't insult language, but it's really cryptic. * 不确定我是否正确使用了C ++代码语法,我不会侮辱语言,但它真的很神秘。 If I've made a mistake, correct me, please 如果我犯了错误,请纠正我

In essence, C++ inference is simplistic compared to the grown ups. 从本质上讲,与成年人相比,C ++推理是简单的。

Functional languages generally something close to Hindley/Milner which is pretty close to solving an equation systems and allow to have unknowns on both sides of the fence. 函数式语言通常接近于Hindley / Milner ,它非常接近求解方程系统并允许在栅栏的两侧都有未知数。

On the contrary, C++ expect to be able to know the type of any inner expression and from that deduce the type of the outer expression. 相反,C ++期望能够知道任何内部表达式的类型,并从中推断出外部表达式的类型。 It's a strictly one way inference, meaning that: 这是一种严格的单向推理,意味着:

auto x = foo(1, 2);

works as expected as long as there is a foo accepting integers and returning non-void. 只要有一个foo接受整数并返回非void,就可以正常工作。 However, as demonstrated by om-nom-nom: 但是,如om-nom-nom所示:

foo(1, [](auto x) { ++x; });

Will not work, because you cannot go backward and use the purported type of foo to deduce the type of the lambda. 无法工作,因为你不能后退并使用声称的foo类型来推断lambda的类型。

The reason behind is that C++ uses overloads of functions, meaning that several definitions of foo could exist, and you actually need to know the types of the arguments to elect the right one. 其背后的原因是C ++使用了函数的重载,这意味着foo几个定义可能存在,并且您实际上需要知道选择正确参数的类型。 Since in general the above expression would be undecidable, it is forbidden even in limited cases it could have been allowed to avoid future maintenance hell and people never knowing when or not it can be used. 由于一般来说上述表达方式是不可判定的,所以即使在有限的情况下也可以禁止它以避免将来的维护地狱,并且人们永远不知道它何时可以被使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM