不可调用项的示例赋值运算符

example assignment operator for non-invokables?

本文关键字:赋值运算符 调用      更新时间:2023-10-16

我有这个赋值运算符用于可调用的f s。

template <typename F>
auto operator=(F&& f) -> decltype(f(), *this);

我还需要一个用于不可调用f,因此在分配这些时不会有歧义。

template<class F>
auto assign_impl(F&& f, int) -> decltype((void) f(), *this) {
    // f() is valid ...
}
template<class F>
auto assign_impl(F&& f, long) -> decltype(*this) {
    // everything else
}
template<class F>
auto operator=(F&& f) -> decltype(*this) { 
    return assign_impl(std::forward<F>(f), 0);
}

我已经将 T.C. 的答案转换为类型特征,现在正在使用它。

namespace
{
template <typename F, typename ...A>
auto f(int) -> decltype(
  (void)::std::declval<F>()(::std::declval<A>()...),
  ::std::true_type{}
);
template <typename F, typename ...A>
auto f(long) -> ::std::false_type;
}
template <typename F, typename ...A>
struct is_invokable : decltype(f<F, A...>(0))
{
};