Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

c++ - get<string> for variants fail under clang++ but not g++

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...