Listings Fertig/always_false

Listing 1: Primäres Klassentemplate Hash mit Spezialisierungen für Cat und Dog
template<typename T>
struct Hash;

template<>
struct Hash<Cat>
{
    static size_t get() { return 1; }
};

template<>
struct Hash<Dog>
{
    static size_t get() { return 2; }
};

-----

Listing 2: Fehlermeldung mit static_assert im primären Klassentemplate Hash
template<typename T>
struct Hash
{
    static_assert(false, "You need to provide a specialization for your type T");
};

-----

Listing 3: Implementierung von always_false in C++11
template<typename... T>
struct always_false
{
    static constexpr bool value = false;
};

-----

Listing 4: Alternative Implementierung von always_false in C++11 mit Funktionsaufrufsyntax
template<typename... T>
constexpr bool always_false()
{
    return false;
}

-----

Listing 5: always_false mit C++14-Variablentemplates
template<typename... T>
struct always_false
{
    static constexpr bool value = false;
};

template<typename... T>
constexpr bool always_false_v = always_false<T...>::value;

static_assert(not always_false_v<int>, "always_false negated");

-----

Listing 6: Hash mit always_false_v in static_assert
template<typename T>
struct Hash
{
    static_assert(always_false_v<T>, "You need to provide a specialization for your type T");
};

-----

Listing 7: Betriebssystemabhängige Init-Funktion
template<typename T>
void Init()
{
    if constexpr(OS::native == OS::Linux) {
        // Linux specific code
      linux_api_call();

    } else if constexpr(OS::native == OS::Mac) {
        // OS X specific code
        mac_api_call();

    } else if constexpr(OS::native == OS::Windows) {
        // Windows specific code
        windows_api_call();

    } else {
        static_assert(false, "Unknown OS");
    }
}

-----

Listing 8: static_assert mit always_false im else-Zweig eines constexpr if
enum class OS
{
    Linux,
    Mac,
    Windows,
    native = Linux
};

template<typename T>
void Init()
{
    if constexpr(OS::native == OS::Linux) {
        // Linux specific code
      linux_api_call();

    } else if constexpr(OS::native == OS::Mac) {
        // OS X specific code
        mac_api_call();

    } else if constexpr(OS::native == OS::Windows) {
        // Windows specific code
        windows_api_call();

    } else {
        static_assert(always_false_v<T>, "Unknown OS");
    }
}

-----

Listing 9: Init mit einem Non-Type-Templateparameter
template<size_t PHASE>
void Init()
{
    if constexpr(0 == PHASE) {
      // ...

    } else {
      static_assert(always_false_v<PHASE>, "Unsupported phase");
    }
}
