演绎指南和注入的班级名称 [英] deduction guides and injected class names

查看:82
本文介绍了演绎指南和注入的班级名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template <typename T>
struct X
{
    template <typename Iter>
    X(Iter a, Iter b) {}

    template <typename Iter>
    auto f(Iter a, Iter b)
    {
        return X(a, b);
    }
};

"C ++模板,完整指南" 第2版中,有一个先前的示例,该示例涉及带有注入的类名的隐式演绎指南的字幕.作者提到对注入的类名禁用类参数推论,因为由于隐式推论指南,f返回的类型为X<Iter>.但是我相信模板构造函数的隐式推导指南看起来像下面的指南.

In the "C++ Templates, The Complete Guide" 2nd edition, there was the previous example about the subtitles of implicit deduction guides with injected class names. The author mentioned that class argument deduction is disabled for injected class names because the type of the return of f would be X<Iter> due to the implicit deduction guide. But I believe the implicit deduction guide for a template constructor would rather look like the one below.

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

我的问题是,在这种情况下,TIter是两个截然不同的类型,并且仅依赖于Iter的参数类型将如何推导类模板参数类型.同样,即使可以通过某种方式推导T,TIter也是独立的,因此从参数推论出Iter并不意味着X具有X<Iter>类型,对吗?书中的文字是否有此错误,还是推导指南看起来与我的想法有所不同?

My question is how would the class template argument types even be deduced in that case T and Iter are two distinct types and the parameters types only rely on Iter. Also even if T could be deduced somehow, T and Iter are independent so deducing Iter from the arguments should not imply that X has type X<Iter> right? Is this some error with the text in the book or should the deduction guide look different from what I thought?

推荐答案

您是正确的.隐式生成的推导指南确实看起来像您编写的指南.模板参数推论永远无法从中推导出T.确实不会造成任何问题.问题出在用户提供的扣除指南上.像这样:

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.

以下是问题的说明:

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

x2是什么类型?如果我们阅读了类模板定义,我们期望它像在C ++ 14中那样是X<float>,但是如果没有关闭类模板参数推导并且添加推论指南,我们将得到

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>!

想象一下现有的代码库,其中的类型在移至C ++ 17之后突然转变.那将是非常糟糕的.

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

这篇关于演绎指南和注入的班级名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆