【问题标题】:Clang and GCC disagree in auto specifier for non-type template parameter in a casting C++17Clang 和 GCC 在强制转换 C++17 中的非类型模板参数的自动说明符中存在分歧
【发布时间】:2018-01-05 02:40:35
【问题描述】:

我基本上有一个依赖于非类型模板参数的类。我定义了一个转换,因此非类型模板参数N 的对象可以转换为M 的另一个对象。我有一个可以重现这种情况的最小示例:

template<auto Integral>
class Test{
    public:
        typedef decltype(Integral) value_type;
        static constexpr value_type N = Integral;

        constexpr Test (const value_type& x = 0);

        template<auto Integral2>
        constexpr explicit operator Test<Integral2>() const;
    private:
        value_type n;
};

template<auto Integral>
constexpr Test<Integral>::Test (const value_type& x){
    if (x < 0){
        n = N - (-x)%N;
    }
    else{
        n = x%N;
    }
}

template<auto Integral> template<auto Integral2>
constexpr Test<Integral>::operator Test<Integral2>() const{
    return Test<Integral2>(n%(Test<Integral2>::N));
}

我在 Ubuntu 16.04 LTS 中使用 GCC 7.2.0 和 Clang 5.0.0 进行编译,并带有 -O2 -std=c++17 标志。

问题是我一直在使用 g++ 进行编译并且一切都按预期工作,但后来我尝试 clang++ 检查一切是否仍然编译正常。

令我惊讶的是,事实并非如此,因为 clang++ 抱怨了一些 g++ 没有的部分。您可以在Compiler Explorer 中查看差异视图。

clang++ 产生的错误消息之一是:

error: out-of-line definition of 'operator Test<Integral2>' does not match any declaration in 'Test<Integral>'

这个让我觉得clang++没有找到一个“正确”的转换声明,但我不知道。

注意:第一个错误仅在将声明与定义分开时出现。否则,它似乎是正确的。

这是 clang++ 产生的第二个错误:

error: a non-type template parameter cannot have type 'auto'

但是这个更让我吃惊,因为这个错误告诉了一些在 C++17 中应该是有效的东西。可能我在这里遗漏了一些东西,因为这对我来说没有意义。

请记住,第二个错误仅在此转换的情况下出现。实际代码中的任何地方都会出现错误(即使有更多 auto 非类型模板参数)。

此时,我有一些问题:

  • 在 clang 编译器的情况下产生错误的原因是什么?
  • 根据标准,哪个是正确的?

【问题讨论】:

  • 我看不出外线定义有什么问题。这似乎是一个 clang 错误。
  • @cdhowie 如果是这样,我应该举报吗?
  • 可能,但我会等待更好的答案。我的评论是基于我对语言的理解的推测;语言律师可能会在接下来的几个小时内给你一个明确的答案。
  • @1201ProgramAlarm 我不想过早下结论,因为我不是专家。我们不能只是假设是 GCC 的错。

标签: c++ g++ language-lawyer clang++ c++17


【解决方案1】:

这是一个clang错误。这是一个简短的复制:

template <int A>
struct X {
    template <auto B>
    X<B> foo();
};

template <int A>
template <auto B>
X<B> X<A>::foo() {
    return {};
}

如果auto Bint B 替换,clang 接受它。 gcc 按原样接受它。对于 clang,这只是嵌套的 template 声明的问题。 auto 作为占位符模板的非类型参数并不会阻止它被用来定义一些异常的东西。

在提交新的 clang 错误时,我发现了 35655,其复制时间更短:

template<typename>
struct S {
    template<auto n>
    static void f() {
        +n;
    }
};

失败:

source.cpp:5:3: error: invalid argument type 'auto' to unary expression
                +n;

【讨论】:

  • 我发现在第二个示例中将+n 更改为+(decltype(n))(n) 以某种方式解决了它...
猜你喜欢
  • 2016-09-15
  • 2019-10-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多