Skip to content

Instantly share code, notes, and snippets.

@Unknown6656
Last active February 27, 2022 21:17
Show Gist options
  • Save Unknown6656/d5bfd62223b7f5007e07397c5284bf17 to your computer and use it in GitHub Desktop.
Save Unknown6656/d5bfd62223b7f5007e07397c5284bf17 to your computer and use it in GitHub Desktop.
An initializer block for constant fields, variables, and members
namespace unknown6656___init_block
{
struct __empty {};
template <class F>
inline decltype(auto) operator+(__empty, F&& f) noexcept
{
return std::forward<F>(f)();
}
}
#define init unknown6656___init_block::__empty{} + [&]() -> decltype(auto)
@Unknown6656
Copy link
Author

This gist allows developers to use an initializer block for constant variables and members

Usage example:

struct C
{
    C(int _i) : i(_i) { }

    const int i;
    const int j = init {
        return 39 + i;
    };
    const std::string k = init {
        std::cout << "class C has been initialized with i=" << i << std::endl;
        return "test!";
    };
};

int main()
{
    C c(3);

    std::cout << c.i << std::endl;
    std::cout << c.j << std::endl;
    std::cout << c.k << std::endl;
}

The code above prints:

class C has been initialized with i=3
3
42
test!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment