C++:在GCC下无法编译std::visit。

6

以下是我的代码,使用clang可以编译通过,但在gcc上失败了。

#include <iostream>
#include <string>
#include <regex>
#include <variant>

struct Id {
    void SetValue(const std::string& item)
    {
        value = item;
    }

    std::string value;
};

struct Number {
    void SetValue(const std::string& item)
    {
        value = std::stoi(item);
    }
    int value;
};


using TokenBase
    = std::variant<Number, Id>;

struct Token : TokenBase {
    using TokenBase::TokenBase;

    template <typename T>
    [[nodiscard]] bool Is() const {
        return std::holds_alternative<T>(*this);
    }

    template <typename T>
    [[nodiscard]] const T& As() const {
        return std::get<T>(*this);
    }

    template <typename T>
    [[nodiscard]] const T* TryAs() const {
        return std::get_if<T>(this);
    }
};

struct LexerTokenExtractor {
    const std::string& item_;

    void operator()(Number& item) const {
        item.SetValue(item_);
    }

    void operator()(Id& item) const {
        item.SetValue(item_);
    }
};


int main()
{
  const std::string string_token("x");
  Token id_token = Id();

  std::visit(LexerTokenExtractor{string_token}, id_token);

  std::cout << "ok" << std::endl;
}

以下是日志:

required from here
/usr/include/c++/7/variant:97:29: error: incomplete type ‘std::variant_size<Token>’ used in nested name specifier
     inline constexpr size_t variant_size_v = variant_size<_Variant>::value;

/usr/include/c++/7/variant: In instantiation of ‘constexpr const auto std::__detail::__variant::__gen_vtable<void, LexerTokenExtractor&&, Token&>::_S_vtable’:
/usr/include/c++/7/variant:711:29:   required from ‘struct std::__detail::__variant::__gen_vtable<void, LexerTokenExtractor&&, Token&>’
/usr/include/c++/7/variant:1255:23:   required from ‘constexpr decltype(auto) std::visit(_Visitor&&, _Variants&& ...) [with _Visitor = LexerTokenExtractor; _Variants = {Token&}]’
1673947047/source.cpp:65:57:   required from here
/usr/include/c++/7/variant:711:49: error: ‘_S_apply’ was not declared in this scope
       static constexpr auto _S_vtable = _S_apply();

请给我任何可能出错的想法。

1
看起来像是 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90943 - cigien
有没有任何解决方法? - Dmitry
@cigien,但你自己的链接中有这个:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2162r2.html。 - SergeyA
@SergeyA 是的,没错 :) 这里可能确实存在一个有效的用例(我还没有读过那篇论文)。但是如果代码无法编译,也许现在不继承(至少在错误被修复之前)是一个合理的方法。 - cigien
@SergeyA 我没有尝试使用boost,因为它在整个项目中都没有被使用。最初我使用clang编写了这段代码,当我面对这个编译错误时感到惊讶。所以我不得不重新设计我的解决方案。感谢您的支持。 - Dmitry
显示剩余2条评论
1个回答

7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接