Skip to content

Instantly share code, notes, and snippets.

@Eczbek
Last active May 10, 2026 00:46
Show Gist options
  • Select an option

  • Save Eczbek/9ef572fbfc3ae00bd6ee11f1b6ab7007 to your computer and use it in GitHub Desktop.

Select an option

Save Eczbek/9ef572fbfc3ae00bd6ee11f1b6ab7007 to your computer and use it in GitHub Desktop.
as
#include<concepts>
#include<utility>
struct as{template<class T>operator T(){std::unreachable();};template<class T>struct t{T&&x;template<class U>[[nodiscard]]constexpr decltype(static_cast<U>((T&&)x))operator->*(U(as::*)())noexcept(noexcept(static_cast<U>((T&&)x))){return static_cast<U>((T&&)x);}};};constexpr auto operator->*(auto&&x,std::same_as<as>auto)noexcept{return as::t((decltype(x))x);}
#define as ->*::as()->*&::as::operator
@Eczbek
Copy link
Copy Markdown
Author

Eczbek commented May 9, 2026

Unlike static_cast, this does not extend the lifetime of a temporary object bound to a reference:

{
    const int& x = static_cast<const int&>(0);
}
// The object is destroyed when the reference goes out of scope

{
    const int& x = 0 as const int&;
    // The object is destroyed at the end of the full-expression
}

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