gpt4 book ai didi

c++ - 强制转换尾随返回类型会导致 SFINAE 失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:52 25 4
gpt4 key购买 nike

出于学习目的,我重新实现了 boost::hana::is_valid。用例是:

struct Person {
std::string name;
};

int main()
{
auto has_name = is_valid([](auto&& t) -> decltype((void) t.name) {});

Person jon{"snow"};
static_assert(has_name(jon), "");
static_assert(!has_name(1), "");
}

实现:

namespace detail {

template<typename F>
struct is_valid_impl {
template<typename T, typename = std::result_of_t<F&&(T&&)>>
constexpr bool operator()(T&&) const noexcept { return true; }

constexpr bool operator()(...) const noexcept { return false; }
};

} // namespace detail

template<typename F>
constexpr auto is_valid(F&&)
{
return detail::is_valid_impl<F>{};
}

但是,我不知道为什么 Hana 的用户指南建议将想要的成员的类型转换为 void(参见 here);我们不能只使用 decltype(t.name) 而不是 decltype((void) t.name) 吗?

此外,转换为 void 会导致测试变为 fail在 GCC < 5.3 中,没有转换代码 works适用于 GCC 5.1+。可能是什么原因?

最佳答案

不能比文档更明确:

@snippet example/tutorial/introspection.cpp non_static_member_from_object

Notice how we cast the result of x.member to void? This is to make sure that our detection also works for types that can't be returned from functions, like array types.

Link to the docs line

关于c++ - 强制转换尾随返回类型会导致 SFINAE 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41829109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com