String-interning at compiletime for profiling

Identical literal strings are not guaranty to be identical, but you can build type from it which can compare identical (without comparing string), something like: // Sequence of char template <char…Cs> struct char_sequence { template <char C> using push_back = char_sequence<Cs…, C>; }; // Remove all chars from char_sequence from ‘\0’ template <typename, char…> struct … Read more

Calculating and printing factorial at compile time in C++

The factorial can be printed in compiler-generated message as: template<int x> struct _; int main() { _<Factorial<10>::value> __; return 0; } Error message: prog.cpp:14:32: error: aggregate ‘_<3628800> __’ has incomplete type and cannot be defined _::value> __; ^ Here 3628800 is factorial of 10. See it at ideone : http://ideone.com/094SJz So are you looking for … Read more

Can a program depend on a library during compilation but not runtime?

A compile-time dependency is generally required at runtime. In maven, a compile scoped dependency will be added to the classpath on runtime (e.g. in wars they will be copied to WEB-INF/lib). It is not, however, strictly required; for instance, we may compile against a certain API, making it a compile-time dependency, but then at runtime … Read more

Does “undefined behaviour” extend to compile-time?

“You’re all ignoring the actual definition and focusing on the note, The standard imposes no requirements.” – @R.MartinhoFernandes The message above was written by the given user in Lounge<C++> and makes a very valid argument; the standard doesn’t impose any requirements when it comes to code that invokes undefined behavior. ! ! ! undefined-behavior stretches … Read more

Detecting Endianness

As stated earlier, the only “real” way to detect Big Endian is to use runtime tests. However, sometimes, a macro might be preferred. Unfortunately, I’ve not found a single “test” to detect this situation, rather a collection of them. For example, GCC recommends : __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ . However, this only works with latest versions, … Read more

Can I obtain C++ type names in a constexpr way?

Well, you could, sort of, but probably not quite portable: struct string_view { char const* data; std::size_t size; }; inline std::ostream& operator<<(std::ostream& o, string_view const& s) { return o.write(s.data, s.size); } template<class T> constexpr string_view get_name() { char const* p = __PRETTY_FUNCTION__; while (*p++ != ‘=’); for (; *p == ‘ ‘; ++p); char const* … Read more

Simplest way to determine return type of function

You can leverage std::function here which will give you an alias for the functions return type. This does require C++17 support, since it relies on class template argument deduction, but it will work with any callable type: using ReturnTypeOfFoo = decltype(std::function{foo})::result_type; We can make this a little more generic like template<typename Callable> using return_type_of_t = … Read more