gpt4 book ai didi

class - 在 C++ 中使用模板或继承构造函数

转载 作者:行者123 更新时间:2023-12-02 21:47:09 25 4
gpt4 key购买 nike

假设我有这个基类:

class Foo public: std::exception
{
public:
// printf()-style parms are formatted with vsnprintf() into a message
Foo( const char * format, ... );
// lots more stuff in this class not relevant to this example
};

现在我需要在许多地方使用它作为基本异常类。然后可以编写 catch() 子句来仅捕获基类,或根据需要捕获某些派生类。

我想做的就是让几十个新类的定义保持非常简单。我正在阅读 C++11 中的继承构造函数,我认为需要遵循以下原则:

class A : public Foo { public: using Foo::Foo; };
class B : public Foo { public: using Foo::Foo; };

问题是这个项目也是使用 Microsoft Visual Studio 在 Windows 中编译的,据我所知 it doesn't support inheriting constructors .

是否有另一种明显的方法可以使派生类保持相对简单?也许用模板?我是模板方面的新手,如果这是正确的方法,我可以朝正确的方向使用。

最佳答案

像这样怎么样:

class Base : public std::exception {};

template <int UNUSED>
class Foo : public Base
{
public:
// printf()-style parms are formatted with vsnprintf() into a message
Foo( const char * format, ... );
// lots more stuff in this class not relevant to this example
};

typedef Foo<1> A;
typedef Foo<2> B;

编辑添加一个基类以便能够捕获所有 Foo 异常。

关于class - 在 C++ 中使用模板或继承构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329131/

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