Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The following code:

variant<string> x = "abc";
cout << get<string>(x) << "
";

works fine under g++ (version 7.2). However, when compiled under clang++ (version 5.0) using libstdc++, I get the following error in the get method:

/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.2.0/../../../../include/c++/7.2.0/variant:238:46: fatal error: cannot cast 'std::variant<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >' to its private base class 'std::__detail::__variant::_Variant_storage<false, std::
__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >'
      return __get(std::in_place_index<_Np>, std::forward<_Variant>(__v)._M_u);

Is this a compiler bug, or is my code illegal in any way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
494 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is caused by clang bug 31852 (and also 33222), whose reproduction courtesy of Jonathan Wakely should look very relevant:

template<typename V> auto get(V&) { }

template<typename>
class variant
{
    template<typename V> friend auto get(V&);
};

int main()
{
  variant<int> v{};
  get(v); // error: ambiguous 
}

clang doesn't properly recognize friend declarations that have placeholder types. Which is exactly how libstdc++ implements std::get:

// Returns the typed storage for __v.
template<size_t _Np, typename _Variant>
constexpr decltype(auto) __get(_Variant&& __v)
{
    return __get(std::in_place_index<_Np>, std::forward<_Variant>(__v)._M_u);
}

this accesses a private member of variant, but this function is properly declared a friend:

template<size_t _Np, typename _Vp>
friend constexpr decltype(auto) __detail::__variant::__get(_Vp&& __v);

libstdc++'s implementation is valid, clang just doesn't think __get is a friend.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...