deduction guides and injected class names

*爱你&永不变心* 提交于 2019-12-05 03:09:37

You are correct. The implicitly generated deduction guide would indeed look like the one you wrote. And template argument deduction could never deduce T from it. That indeed won't cause a problem. The problem is with user supplied deduction guides. Like this:

template <typename Iter>
X(Iter a, Iter b) -> X<typename Iter::value_type>;

Which are often added to allow class template argument deduction from iterators. That one could wreak havoc if the injected class name did not suppress argument deduction. The authors may have overlooked the need to add that deduction guide to demonstrate the problem.

Here's an illustration of the problem:

auto v = std::vector<int>{1, 2};
auto x1 = X<float>(begin(v), end(v));
auto x2 = x1.f(begin(v), begin(v));

What's the type of x2? If we read the class template definition, we expect it to be X<float> as it would be in C++14, but if class template argument deduction isn't turned off and we add our deduction guide, we'll get X<int>!

Imagine existing code bases where types suddenly shifted after moving to C++17. That would be very bad.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!