【问题标题】:Why can't the compiler deduce auto template parameter unless I add const?除非我添加 const,否则编译器为什么不能推导出自动模板参数?
【发布时间】:2017-12-18 07:25:35
【问题描述】:

我最近遇到了这样的代码问题:

constexpr auto lambda = []{};

template<auto& l>
struct Lambda {};

template<auto& l>
void test(Lambda<l>) {}

int main() {
    test(Lambda<lambda>{});
}

clang 和 GCC 都告诉它不能推断出l

但是,如果我在那里添加 const:

//   ----v
template<const auto& l>
void test(Lambda<l>) {}

然后一切都与clang一起工作。 GCC 仍然失败。这里发生了什么事?不能自己推断const吗?在这两种情况下都没有推断出 l 是 GCC 错误吗?

【问题讨论】:

    标签: c++ templates language-lawyer c++17 template-argument-deduction


    【解决方案1】:

    这是一个 GCC 错误,因为它在这两种情况下都没有推导出 l 吗?

    这是一个错误,对于 Clang 也是如此。对于占位符类型的非类型参数,[temp.arg.nontype]/1 说:

    如果模板参数的类型包含占位符类型, 推导的参数类型由 模板参数按占位符类型推导。如果推导 模板参数声明不允许参数类型 ([temp.param]),程序格式错误。

    这里的推理过程完全相同

    int main() {
       auto& l = lambda;
    }
    

    l 是常量引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      相关资源
      最近更新 更多