【问题标题】:C++ noexcept unknown member functionC++ noexcept 未知成员函数
【发布时间】:2016-06-26 05:21:56
【问题描述】:
#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>())))

(但是会出现编译错误。)
这样用户就可以指定应该使用哪个成员函数。

在不知道应该提前调用哪个成员函数的情况下有任何可能这样做吗?

【问题讨论】:

    标签: c++ expression noexcept


    【解决方案1】:

    如果你使用另一个参数来指定函数,它会起作用。

    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;
    

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

    完整代码 here, 如果需要更多上下文。

    【讨论】:

    • 虽然这不是我想要的,但这似乎是唯一的方法。
    猜你喜欢
    • 2023-03-05
    • 2012-10-14
    • 1970-01-01
    • 2015-10-04
    • 2012-08-20
    • 2014-04-02
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多