问题描述
我将此代码与std=c++14
和gcc7.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
限定符删除到变量声明中即可。