Skip to content

Instantly share code, notes, and snippets.

@Eczbek
Last active July 15, 2026 14:34
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
struct as{template<class T>operator T(){throw;};template<class T>struct x{T x;template<class U>constexpr decltype(static_cast<U>((T)x))operator->*(U(as::*)())noexcept(noexcept(static_cast<U>((T)x))){return static_cast<U>((T)x);}};template<class T>friend constexpr x<T&&>operator->*(T&&x,as)noexcept{return{(T&&)x};}};
#define as ->*::as()->*&::as::operator
@Eczbek

Eczbek commented May 9, 2026

Copy link
Copy Markdown
Author

Requires C++11 minimum

Example:

static_assert(3.5 as int == 3);

https://godbolt.org/z/nfbY9Yh7K

 

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
}

 

(Wrongly rejected by GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=122383)

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