mirror of
https://github.com/cirosantilli/linux-kernel-module-cheat.git
synced 2026-01-24 02:35:58 +01:00
learn more c++, it never ends
This commit is contained in:
@@ -1,20 +1,18 @@
|
||||
// https://cirosantilli.com/linux-kernel-module-cheat#cpp
|
||||
|
||||
#include <cassert>
|
||||
|
||||
int main() {
|
||||
|
||||
struct D {
|
||||
int i;
|
||||
D() {}
|
||||
D(int i) : i(i) {}
|
||||
constexpr D() : i(0) {}
|
||||
constexpr D(int i) : i(i) {}
|
||||
};
|
||||
|
||||
struct C {
|
||||
int i;
|
||||
C() : i(1) {}
|
||||
C(int i) : i(i) {}
|
||||
C(const D& d) : i(d.i) {}
|
||||
constexpr C() : i(1) {}
|
||||
constexpr C(int i) : i(i) {}
|
||||
constexpr C(const D& d) : i(d.i) {}
|
||||
};
|
||||
|
||||
// Declares *FUNCTION* called `c` that returns `C` inside function main.
|
||||
@@ -25,7 +23,7 @@ int main() {
|
||||
// Therefore there would be not way for C++ to distinguish between the two,
|
||||
// and still be backwards compatible with C.
|
||||
{
|
||||
C c();
|
||||
constexpr C c();
|
||||
|
||||
#if 0
|
||||
// ERROR: function definition is not possible inside another function.
|
||||
@@ -37,24 +35,24 @@ int main() {
|
||||
|
||||
// If you want to call a default constructor, use:
|
||||
{
|
||||
C c;
|
||||
assert(c.i == 1);
|
||||
constexpr C c;
|
||||
static_assert(c.i == 1);
|
||||
}
|
||||
|
||||
// For non-default constructors, literal arguments disambiguate
|
||||
// things as this syntax could not possibly be a function declaration.
|
||||
{
|
||||
C c(2);
|
||||
assert(c.i == 2);
|
||||
constexpr C c(2);
|
||||
static_assert(c.i == 2);
|
||||
}
|
||||
|
||||
// But sometimes even arguments are not enough: here D()
|
||||
// is interpreted as "a function of type `D f()`"
|
||||
{
|
||||
C c(D(2));
|
||||
constexpr C c(D());
|
||||
#if 0
|
||||
// error: request for member ‘i’ in ‘c’, which is of non-class type ‘main()::C(main()::D (*)())’
|
||||
assert(c.i == 2);
|
||||
static_assert(c.i == 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -63,22 +61,22 @@ int main() {
|
||||
{
|
||||
// Extra parenthesis.
|
||||
{
|
||||
C c((D(2)));
|
||||
assert(c.i == 2);
|
||||
constexpr C c((D(2)));
|
||||
static_assert(c.i == 2);
|
||||
}
|
||||
|
||||
// Initialize through assignment. TODO likely guaranteed to be cost-free,
|
||||
// but confirm.
|
||||
{
|
||||
C c = C((D(2)));
|
||||
assert(c.i == 2);
|
||||
constexpr C c = C((D(2)));
|
||||
static_assert(c.i == 2);
|
||||
}
|
||||
|
||||
// Initializer list. Only works if there is no initializer_list constructor.
|
||||
// Only works in general if c does not have an ambiguous initializer_list constructor though.
|
||||
{
|
||||
C c{D(2)};
|
||||
assert(c.i == 2);
|
||||
constexpr C c{D(2)};
|
||||
static_assert(c.i == 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user