boost :: hana :: is_valid无法使用gcc8及更多和--std = c ++ 14编译

问题描述

我将此代码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中添加一个bug?

解决方法

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

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

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...