本文介绍了过载解析:分配空括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我写了一些代码 S s; ... s = {}; ,期望它结束与 S s = {}; 相同。但事实并非如此。以下示例重现了该问题:I wrote some code S s; ... s = {};, expecting it to end up the same as S s = {};. However it didn't. The following example reproduces the problem:#include <iostream>struct S{ S(): a(5) { } S(int t): a(t) {} S &operator=(int t) { a = t; return *this; } S &operator=(S const &t) = default; int a;};int main(){ S s = {}; S t; t = {}; std::cout << s.a << '\n'; std::cout << t.a << '\n';}输出为:50我的问题是: 为什么在这里选择 operator =(int)而不是模棱两可 还是其他? 是否有一个整洁的解决方法,而无需更改 S ?Why is operator=(int) selected here, instead of "ambiguous" or the other one?Is there a tidy workaround, without changing S?我的意图是 s = S {}; 。编写 s = {}; 会很方便。我目前正在使用 s = decltype(s){}; ,但是我希望避免重复输入类型或变量名。My intent is s = S{}; . Writing s = {}; would be convenient if it worked. I'm currently using s = decltype(s){}; however I'd prefer to avoid repeating the type or the variable name.推荐答案 {} 到 int 是身份转换( [over.ics.list] / 9 )。 {} 到 S 是用户定义的转换( [over.ics.list] / 6 )(从技术上讲,它是 {} 到 const S& ,先经过[over.ics.list] / 8和[over.ics.ref],然后再返回[over.ics.list] / 6){} to int is the identity conversion ([over.ics.list]/9). {} to S is a user-defined conversion ([over.ics.list]/6) (technically, it's {} to const S&, and goes through [over.ics.list]/8 and [over.ics.ref] first before coming back to [over.ics.list]/6).第一个胜利。技巧的变体 std :: experimental :: optional 拉动使 t = {} 始终使 t 为空。 关键是使 operator =(int)成为模板。如果您只想接受 int ,而只接受 int ,则它将变为A variation of the trick std::experimental::optional pulls to make t = {} always make t empty.The key is to make operator=(int) a template. If you want to accept int and only int, then it becomestemplate<class Int, std::enable_if_t<std::is_same<Int, int>{}, int> = 0>S& operator=(Int t) { a = t; return *this; }如果要启用转化,可以使用不同的约束(您可能还想采用Different constraints can be used if you want to enable conversions (you'd probably also want to take the argument by reference in that case).要点是,通过将右操作数的类型作为模板参数,可以阻止 t = {} 使用此重载-因为 {} 是非推论上下文。The point is that by making the right operand's type a template parameter, you block t = {} from using this overload - because {} is a non-deduced context. template< class T>是否会T default_constructed_instance_of(const T&){return {}; } ,然后 s = default_constructed_instance_of(s); count?Does template<class T> T default_constructed_instance_of(const T&) { return {}; } and then s = default_constructed_instance_of(s);count? 这篇关于过载解析:分配空括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 13:46