【发布时间】:2016-06-17 01:56:12
【问题描述】:
在C++11及以后,如何判断抽象基类的构造函数是否为noexcept?以下方法无效:
#include <new>
#include <type_traits>
#include <utility>
struct Base { Base() noexcept; virtual int f() = 0; };
// static assertion fails, because !std::is_constructible<Base>::value:
static_assert(std::is_nothrow_constructible<Base>::value, "");
// static assertion fails, because !std::is_constructible<Base>::value:
static_assert(std::is_nothrow_default_constructible<Base>::value, "");
// invalid cast to abstract class type 'Base':
static_assert(noexcept(Base()), "");
// invalid new-expression of abstract class type 'Base'
static_assert(noexcept(new (std::declval<void *>()) Base()), "");
// cannot call constructor 'Base::Base' directly:
static_assert(noexcept(Base::Base()), "");
// invalid use of 'Base::Base':
static_assert(noexcept(std::declval<Base &>().Base()), "");
一个简单的用途是:
int g() noexcept;
struct Derived: Base {
template <typename ... Args>
Derived(Args && ... args)
noexcept(noexcept(Base(std::forward<Args>(args)...)))
: Base(std::forward<Args>(args)...)
, m_f(g())
{}
int f() override;
int m_f;
};
关于如何归档这个或者在不修改抽象基类的情况下是否有可能?
PS:也欢迎任何对 ISO C++ 缺陷报告或正在进行的工作的引用。
编辑: 正如两次指出的那样,将 Derived 构造函数默认为 = default 会使 noexcept 被继承。但这并不能解决一般情况下的问题。
【问题讨论】:
-
如果你知道抽象方法,你可以像this那样做。如果您想要一个完全通用的解决方案,我认为您不走运
标签: c++ c++11 c++14 c++17 noexcept