C++ check if statement can be evaluated constexpr

Here’s another solution, which is more generic (applicable to any expression, without defining a separate template each time). This solution leverages that (1) lambda expressions can be constexpr as of C++17 (2) the type of a captureless lambda is default constructible as of C++20. The idea is, the overload that returns true is selected when …

Read more

How to instantiate only part of a function template if a condition is true

Type traits: #include <iostream> #include <type_traits> // C++0x //#include <tr1/type_traits> // C++03, use std::tr1 template<typename T> void printType(T param) { if(std::is_same<T,char*>::value) std::cout << “char*” << endl; else if(std::is_same<T,int>::value) std::cout << “int” << endl; else std::cout << “???” << endl; } Or even better yet, just overload the function: template<class T> void printType(T partam){ std::cout << …

Read more

“constexpr if” vs “if” with optimizations – why is “constexpr” needed?

This is easy to explain through an example. Consider struct Cat { void meow() { } }; struct Dog { void bark() { } }; and template <typename T> void pet(T x) { if(std::is_same<T, Cat>{}){ x.meow(); } else if(std::is_same<T, Dog>{}){ x.bark(); } } Invoking pet(Cat{}); pet(Dog{}); will trigger a compilation error (wandbox example), because both …

Read more