代码之家  ›  专栏  ›  技术社区  ›  Guillaume Racicot

为什么编译器不能推断自动模板参数,除非我添加常量?

  •  9
  • Guillaume Racicot  · 技术社区  · 7 年前

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

    constexpr auto lambda = []{};
    
    template<auto& l>
    struct Lambda {};
    
    template<auto& l>
    void test(Lambda<l>) {}
    
    int main() {
        test(Lambda<lambda>{});
    }
    

    clang和GCC都表示无法推断 l .

    但是,如果在此处添加常量:

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

    然后一切都在叮当作响。GCC仍然失败。这里发生了什么事?它不能推断出 const 它本身这是一个GCC错误吗 l 在这两种情况下?

    1 回复  |  直到 7 年前
        1
  •  8
  •   StoryTeller - Unslander Monica    7 年前

    在这两种情况下都不推断l,这是GCC的错误吗?

    这是一只虫子,对叮当声来说也是。对于占位符类型的非类型参数, [temp.arg.nontype]/1 说:

    如果模板参数的类型包含占位符类型, 这个 推断的参数类型由 按占位符类型推断的模板参数 . 如果推导出 模板参数声明不允许使用参数类型 ([温度参数]),程序格式错误。

    这和它在这里推导的过程是一样的

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

    那个 l 是常量引用。