通过抽象类我的意思是具有至少一个纯虚方法的类.如果检查显示该类不是抽象的,我希望编译失败.
它甚至可能吗?
我有一个类似于以下代码:
try:
something()
except DerivedException as e:
if e.field1 == 'abc':
handle(e)
else:
# re-raise with catch in the next section!
except BaseException as e:
do_some_stuff(e)
Run Code Online (Sandbox Code Playgroud)
从何DerivedException而来BaseException.
所以,就像代码中的注释一样 - 我想从第一部分内部重新引发异常except并在第二部分内再次捕获它except.
怎么做?
我想实现一个简单的运行时检查宏,所以它的工作方式如下:
CHECK(expr) << "Some problem!";
Run Code Online (Sandbox Code Playgroud)
我写了一个简化的日志记录类来做到这一点:
class Log {
public:
Log() = default;
Log(const Log&) = delete;
~Log() {
cout << this << " dtor" << endl;
cout << stream_.str() << endl;
}
template <class T>
Log& operator<<(const T& info) {
cout << this << " <<" << endl;
stream_ << info;
return *this;
}
private:
stringstream stream_;
};
Run Code Online (Sandbox Code Playgroud)
让宏观:
#define CHECK(expr) \
if (!(expr)) [] { /* See attempts below */ }()
Run Code Online (Sandbox Code Playgroud)
现在让我们尝试实现lambda.
最简单的方法应该是:
[] {
Log log; …Run Code Online (Sandbox Code Playgroud) 我有一个简单的例子:
struct A {
explicit A(int a) : a(a) {}
protected:
int a;
};
struct B : public A { int b = 0, c = 0; };
// Attempts to get the code compiled:
B b1 { A(1), .c = 2 }; // fine with clang-11
B b2 { A{1}, .c = 2 };
B b3 { .A{1}, .c = 2 };
B b4 { {1}, .c = 2 };
B b5 { .a = 1, .c = 2 …Run Code Online (Sandbox Code Playgroud)