【问题标题】:g++7.2.0 fails auto non-type parameter deductiong++7.2.0 自动非类型参数推导失败
【发布时间】:2017-12-28 17:23:37
【问题描述】:

我正在尝试使用自动非类型参数 (c++17)。 我预计“Sample1::type”应该是“integral_constraint”,但它与“Sample0::type”相同。

是 g++ 错误还是我对该功能的误解? 我在 Ubuntu 17.10 上使用 g++ (Ubuntu 7.2.0-8ubuntu3) 7.2.0。

-- auto_param.cxx --
#include <iostream>
#include <type_traits>
#include <boost/type_index.hpp>

template <auto V>
struct Value {
  using type = std::integral_constant<decltype(V), V>;
};

template <typename T>
auto demangle() {
  return boost::typeindex::type_id_with_cvr<T>().pretty_name();
}

void zero_as_uint() {
  using Sample0 = Value<0u>;
  std::cout << __func__ << ": " << demangle<Sample0::type>() << std::endl;
}

void zero_as_int() {
  using Sample1 = Value<0>;
  std::cout << __func__ << ": " << demangle<Sample1::type>() << std::endl;
}

int main(int, char**) {
  zero_as_uint();
  zero_as_int();
  return 0;
}
-----------------------------
$ g++ -Wall -std=c++17 auto_param.cxx && ./a.out
zero_as_uint: std::integral_constant<unsigned int, 0u>
zero_as_int: std::integral_constant<unsigned int, 0u>

我发现 clang++ 的推导符合我的预期。

$ clang++-5.0 -Wall -std=c++17 auto_param.cxx && ./a.out
zero_as_uint: std::integral_constant<unsigned int, 0u>
zero_as_int: std::integral_constant<int, 0>

【问题讨论】:

  • 模板 是一种表示 T 可以是类型或非类型的新方式吗?我习惯在那里看到“class”或“typename”
  • @Zebrafish 或者,它必须是一个变量,你可能在那里见过int,对吧?嗯,这里也是一样的,只是类型被推导出来了。
  • 在 gcc 8.0 之前我们不应该使用这个特性。谢谢!

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


【解决方案1】:

那是bug in gcc。进一步简化的示例如下所示:

#include <type_traits>

template <auto V>
struct Value {
  using type = std::integral_constant<decltype(V), V>;
};

static_assert(!std::is_same_v<Value<0u>::type, Value<0>::type>);

这两种类型不可能相同,因为它们引用了不同的模板实例化。看起来像 gcc has always had the bug,但在最新的主干中是固定的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2018-05-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 2017-05-06
    相关资源
    最近更新 更多