【问题标题】:boost::hana::is_valid fails to compile with gcc8 (and more) and --std=c++14boost::hana::is_valid 无法使用 gcc8(及更多)和 --std=c++14 编译
【发布时间】:2021-01-09 09:34:35
【问题描述】:

我将此代码与std=c++14gcc7.3 一起使用:

#include <iostream>
#include <string>
#include <type_traits>
#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/type.hpp>
namespace hana = boost::hana;

template<class T>
bool foo(T elem)
{
    constexpr auto has_overload_to_string = hana::is_valid([](auto t) -> decltype(to_string(t)) {});
    constexpr bool hasOverloadTo_string = has_overload_to_string(elem);
    return hasOverloadTo_string;
}

int main()
{ 
    std::string elem;
    std::cin >> elem;
    foo(elem);
}  

而且效果很好:demo

如果我现在使用 gcc10.1,我得到了这个错误:demo fail

prog.cc: In instantiation of 'bool foo(T) [with T = std::__cxx11::basic_string<char>]':
prog.cc:41:13:   required from here
prog.cc:27:38: error: temporary of non-literal type 'foo<std::__cxx11::basic_string<char> >::<lambda(auto:1)>' in a constant expression
   27 |      [[maybe_unused]] constexpr auto has_overload_to_string =
      |                                      ^~~~~~~~~~~~~~~~~~~~~~
prog.cc:28:21: note: 'foo<std::__cxx11::basic_string<char> >::<lambda(auto:1)>' is not literal because:
   28 |      hana::is_valid([](auto t) -> decltype(to_string(t)) {});
      |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1plus: note:   'foo<std::__cxx11::basic_string<char> >::<lambda(auto:1)>' is a closure type, which is only literal in C++17 and later 

我的问题是:gcc7.3 是否对 C++14 过于宽容,is_valid 在不应该的情况下工作还是 gcc8 和更多添加了 C++14 的错误?

【问题讨论】:

  • 我不知道 wandbox 是如何管理这个的,但是在 Godbolt 上它对于所有版本都是错误的 >8.0。 C++17 放宽了对 lambdas 的限制,以便再次编译。
  • 确实,我会更新我的帖子。谢谢提供信息

标签: c++14 language-lawyer template-meta-programming boost-hana gcc7


【解决方案1】:

该错误与hana::is_valid无关,但lambda在C++14的常量表达式中无效。

这里已经有一个很好的语言律师回答: https://stackoverflow.com/a/32697323/800347

Clang 也始终提供错误,因此很明显以前版本的 gcc 不允许这样做是不正确的。

要解决此问题,只需将 constexpr 限定符删除到您的变量声明中。

【讨论】:

  • 谢谢,我错过了可以在 constexpr 声明中使用非 constexpr lambda 的事实!效果很好:godbolt.org/z/bvEMvK
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2014-07-11
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多