gpt4 book ai didi

c++ - 当我从我的继承列表中选择一个特定的隐藏函数时,我如何使用 noexcept?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:12:45 26 4
gpt4 key购买 nike

为了避免重复相似的函数定义,我使用了这样一个事实,即具有相同名称的继承成员是隐藏的,并且可以通过使用特定的基类限定符来选择/区分:

#include <type_traits>

template<template<class, class> class CreatePolicy, class Base, class... Derived>
class factory : public CreatePolicy<Base, Derived>...
{
public:
template
<
class T,
std::enable_if_t
<
!std::is_same<Base, T>::value && std::is_base_of<Base, T>::value, int
> = 0
>
std::unique_ptr<Base> create() noexcept( noexcept( CreatePolicy<Base, T>::create() ) )
{
return CreatePolicy<Base, T>::create();
}
};

使用它看起来像这样:

#include <memory>
#include <cassert>

template<class Base, class Derived>
struct create_t
{
auto create()
{
return std::make_unique<Derived>();
}
};

struct base
{
virtual void print() const noexcept
{
std::cout << "base\n";
}
};

struct derived : public base
{
virtual void print() const noexcept override
{
std::cout << "derived\n";
}
};

int main()
{
factory<create_t, base, derived> f;
auto d = f.create<derived>();
d->print();
}

虽然在 VC++2015 下编译,但由于 create()noexcept 规范,GCC5.1 给我这个错误:

..\main.cpp|20|error: cannot call member function 'auto
create_t<T>::create() [with T = derived]' without object|

如何编译?

最佳答案

语法 base_class::method(...) 调用基类的成员函数只在成员函数体内有效。这特别排除了未评估的上下文,例如它们出现在 noexcept 规范中。然而,这些上下文的美妙之处在于它们就是:未评估。所以你可以以某种方式获取你的类的一个实例并调用它的方法。执行此操作的标准方法是使用 std::declval:

std::unique_ptr<Base> create() noexcept( noexcept( std::declval<CreatePolicy<Base, T>&>().create() ) )

关于c++ - 当我从我的继承列表中选择一个特定的隐藏函数时,我如何使用 noexcept?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38295607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com