C++ 非可调用的赋值运算符示例?
对于可调用的C++ 非可调用的赋值运算符示例?,c++,c++14,c++17,C++,C++14,C++17,对于可调用的fs,我有这个赋值运算符 template <typename F> auto operator=(F&& f) -> decltype(f(), *this); 模板 自动运算符=(F&&F)->decltype(F(),*this); 对于不可调用的fs,我也需要一个,这样在分配这些时就不会有歧义。模板 template<class F> auto assign_impl(F&& f, int) -> dec
f
s,我有这个赋值运算符
template <typename F>
auto operator=(F&& f) -> decltype(f(), *this);
模板
自动运算符=(F&&F)->decltype(F(),*this);
对于不可调用的f
s,我也需要一个,这样在分配这些时就不会有歧义。模板
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);
}
自动赋值\u impl(F&&F,int)->decltype((void)F(),*this){
//f()是有效的。。。
}
模板
自动分配\u impl(F&&F,long)->decltype(*this){
//其他一切
}
模板
自动运算符=(F&&F)->decltype(*this){
返回赋值impl(std::forward(f),0);
}
我已经将T.C.s.的答案转化为一种类型特征,现在正在使用它
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))
{
};
名称空间
{
模板
自动f(int)->decltype(
(void)::std::declval()(::std::declval()…),
::std::true_type{}
);
模板
自动f(长)->::标准::错误类型;
}
模板
结构是可调用的:decltype(f(0))
{
};
只在内部分派。int重载不总是被调用吗?@user1095108只有在f()
是有效表达式时才调用。否则它就出局了。是的,是的,我现在明白了。为什么要强制转换为空?@user1095108防止逗号过多。嘿,如果你想要一个特征,void\u t
技巧可能更干净。这种特征在@t.C.的路上。请扩展你的答案