C++ no除了未知成员函数


#include<iostream>
#include<utility>
using namespace std;
struct A
{
    void set(const int &){}
    void set(int &&) noexcept
    {}
};
template<class Assign,class T,class Func>
struct B
{
    B& operator=(const Assign &)
    {
        return *this;
    }
    B& operator=(Assign &&) noexcept(noexcept(declval<T>().set(declval<Assign>())))
    {
        return *this;
    }
};
int main()
{
    cout<<is_nothrow_assignable<B<int,A,void(A::*)(int &&)>&,int&&>::value<<endl;
}

我想做线

B& operator=(Assign &&) noexcept(noexcept(declval<T>().set(declval<Assign>())))


B& operator=(Assign &&) noexcept(noexcept(declval<T>().Func(declval<Assign>())))

(但它会发生编译错误。
以便用户可以指定应使用哪个成员函数。

在不知道应该提前调用哪个成员函数的情况下,是否有可能做到这一点?

如果使用其他参数指定函数,它将起作用。

template<class Assign,class T,class Func, Func f> struct B
//...
B& operator=(Assign &&) noexcept(noexcept((declval<T>().*f)(declval<Assign>())))
//...
cout<<is_nothrow_assignable<B<int,A,void(A::*)(int &&), &A::set>&,int&&>::value<<endl;

Func非类型参数添加到B,在 noexcept 运算符中使用成员函数指针调用语法,然后可以通过传递指向函数的指针来指定函数。

如果它需要更多的上下文,请在此处使用完整代码。

最新更新