Why doesn’t this “undefined extern variable” result in a linker error in C++17?

Because the variable isn’t odr-used. You have a constexpr if there that always discards the branch that could use it. One of the points of constexpr if is that the discarded branch need not even compile, only be well-formed. That’s how we can place calls to non-existing member functions in a discarded branch.

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

Equivalent ternary operator for constexpr if?

No, there is no constexepr conditional operator. But you could wrap the whole thing in a lambda and immediately evaluate it (an IIFE): template<typename Mode> class BusAddress { public: explicit constexpr BusAddress(Address device) : mAddress([&]{ if constexpr (Mode::write) { return device.mDevice << 1; } else { return (device.mDevice << 1) | 0x01; } }()) { … Read more