在C++ 11及更高版本中,如何确定抽象基类的构造函数是否为noexcept
?下面的方法不起作用:确定抽象基类的构造函数是否为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;
};
有关如何archieve这还是有可能的任何想法都无需修改的抽象基类? PS:所有对ISO C++缺陷报告或正在进行的工作的引用也是受欢迎的。
编辑:正如指出的两次,= default
使得noexcept
拖欠Derived
构造继承。但这并不能解决一般情况下的问题。
如果你知道抽象方法,你可以像[this]一样做(http://coliru.stacked-crooked.com/a/99ee522df4a1c7c7)。如果你想要一个完全通用的解决方案,我认为你运气不好 – sp2danny