【问题标题】:Non-type template parameter type changes randomly非类型模板参数类型随机变化
【发布时间】:2019-11-15 02:48:13
【问题描述】:

我不确定这是否是编译器错误,或者我是否做了违反标准的事情导致未定义的行为。这是我的代码:

#include <iostream>
template<auto InputSize, typename SizeType = decltype(InputSize)>
class StaticArray
{
public:
    using size_type = SizeType;
    using size_type2 = decltype(InputSize);
};

int main()
{
    //StaticArray<2, int> s1;
    StaticArray<2ull, int> s3;
    std::cout << typeid(decltype(s3)::size_type).name() << "\t" << typeid(decltype(s3)::size_type2).name() << "\n";
    return 0;
}

如果注释掉的行仍然被注释掉,我会得到正确的输出:int unsigned __int64。但是,如果我取消注释该行,我会得到输出 int int。作为参考,我在 MSVC 2017 v15.9.2 上的 x86 调试中编译它。

【问题讨论】:

  • 这看起来像是一个明显的编译器错误。
  • s1 与以下几行无关。必须是一个错误。
  • @L.F.我不确定我是否违反了有关模板的规定(我今天才知道我可以在模板参数列表中使用 auto),这导致了 UB.如果它确实是一个错误,我会报告给 MS。
  • 模板中的 auto 在所有编译器中仍然是一个实验性功能。所以有时它可能不起作用。
  • @Zefick 实验性的?虽然它是 C++17...

标签: c++ templates visual-c++ c++17 non-type


【解决方案1】:

它看起来像一个编译器错误,请参阅https://godbolt.org/z/k2ng-1。如果 MSVC 的版本小于或等于 19.16,则存在您显示的问题,从 19.20 开始一切正常。

编辑:如果链接将来断开,请在测试代码下方:

#include <type_traits>

template<auto InputSize, typename SizeType = decltype(InputSize)>
class StaticArray
{
public:
    using size_type = SizeType;
    using size_type2 = decltype(InputSize);
};

int main()
{
    StaticArray<2, int> s1;
    StaticArray<2ull, int> s3;

    static_assert(std::is_same_v<decltype(s3)::size_type, int>, "ERROR 1");
    static_assert(std::is_same_v<decltype(s3)::size_type2, unsigned long long>, "ERROR 2");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多