Expanding parameter pack into lambda with fold expression - gcc vs clang

依然范特西╮ 提交于 2019-12-01 17:20:16

This is an old gcc bug. It is one of the few cases where gcc's template handling is worse than MSVC. Shame gcc. Shame.

A workaround that sometimes works is to use tags and pack expansion.

template<class T>struct tag_t{using type=T; constexpr tag_t(){};};
template<class T>constexpr tag_t<T> tag{};
template<class Tag>using type_t=typename Tag::type;
#define TAG2TYPE(...) type_t<decltype(__VA_ARGS__)>

// takes args...
// returns a function object that takes a function object f
// and invokes f, each time passing it one of the args...
template<class...Args>
auto expand( Args&&...args ) {
  return [&](auto&& f)->decltype(auto) {
    using discard=int[];
    (void)discard{0,(void(
      f( std::forward<Args>(args) )
    ),0)...};
  };
}

template <typename TF>
void post(TF){ }

template <typename... TFs>
struct funcs : TFs...
{
  funcs(TFs... fs) : TFs{fs}... { }

  void call()  { 
    expand( tag<TFs>... )
    ([&](auto tag){
      post(static_cast< TAG2TYPE(tag)& >(*this)());
    });
  }
};

where we carefully avoid expanding over the end of a lambda by passing the lambda in each time. Instead, we take a set of arguments and expand it into a set of lambda calls.

The lambda gets the types passed in as a tag, then we convert it back to a type.

Live example

Do not store return type of expand if you passed it temporaries.

This is a well-known g++ bug (#47226) that was reported in... 2011.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!