c++ - 在扣除 auto 之前使用 boost::hana::eval_if_t

标签 c++ c++14 auto 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;
}

编译错误是:

$> 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);
            ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

没有递归,我使用 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>;

将其强制转换为bool 意味着该类型不再携带值信息。使用自动

关于c++ - 在扣除 auto 之前使用 boost::hana::eval_if_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44207315/

相关文章:

c++ - 方法参数的内存错误(访问冲突)

c++ - 如何自定义打开/保存文件对话框?

c++ - 引用初始化表格

c++ - 编译器如何选择给 auto 赋值?

c++ - 类中未初始化的常量成员

c++ - GCC,clang 不同意 MSVC 缩小转换

c++ - 为什么C++ 11不允许使用auto进行直接列表初始化

c++ - 是否可以使用默认泛型参数在 C++ 中定义 lambda?

c++ - 如何分配字符串文字

c++ - 为什么这个范围基于语句返回一个太低的数字?