Per*_*-lk 1 c++ auto c++14 boost-hana
代码段说明了几个段落:
#include <boost/hana/fwd/eval_if.hpp>
#include <boost/hana/core/is_a.hpp>
#include <iostream>
#include <functional>
using namespace boost::hana;
template<class arg_t>
decltype(auto) f2(arg_t const& a)
{
constexpr bool b = is_a<std::reference_wrapper<std::string>,
arg_t>;
auto wrapper_case = [&a](auto _) -> std::string&
{ return _(a).get(); };
auto default_case = [&a]() -> arg_t const&
{ return a; };
return eval_if(b, wrapper_case, default_case);
}
int main()
{
int a = 3;
std::string str = "hi!";
auto str_ref = std::ref(str);
std::cout << f2(a) << ", " << f2(str) << ", " << f2(str_ref)
<< std::endl;
}
Run Code Online (Sandbox Code Playgroud)
编译器错误是:
$> g++ -std=c++14 main.cpp
main.cpp: In instantiation of ‘decltype(auto) f2(const arg_t&) [with arg_t = int]’:
main.cpp:42:22: required from here
main.cpp:31:19: error: use of ‘constexpr decltype(auto) boost::hana::eval_if_t::operator()(Cond&&, Then&&, Else&&) const [with Cond = const bool&; Then = f2(const arg_t&) [with arg_t = int]::<lambda(auto:1)>&; Else = f2(const arg_t&) [with arg_t = int]::<lambda(auto:2)>&]’ before deduction of ‘auto’
return eval_if(b, wrapper_case, default_case);
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
没有递归,我使用gcc-6.0.2,它可能已经解决了一些错误decltype(auto)并且具有完整的C++ 14实现,并且也符合boost::hana要求,所以,我的错误必须在我的实现中但我不知道什么是错误.
注意:clang ++ 3.8.0会抛出类似的编译器错误.
首先,如果路径没有说清楚,boost/hana/fwd/eval_if.hpp只是一个前向声明.如果你想认真使用它,你需要包括整个事物,即boost/hana/eval_if.hpp.这是原始错误的原因.
那么,这bool是错误的:
constexpr bool b = is_a<std::reference_wrapper<std::string>,
arg_t>;
Run Code Online (Sandbox Code Playgroud)
强制它bool意味着该类型不再携带价值信息.使用auto.