C++ Templates != Java Generics

2018-08-24 ☼ codingc++

C++ templates are way more powerful than Java’s generics.

A simple example is to change the return-type of a function depending on template parameters:

template<
    typename T = int,
    bool     Required = true,
    typename OUT = typename std::conditional_t<Required, T, std::optional<T>>
>
OUT getFromCache(std::string&amp; key) {
    return {};
}

int main() {
    int somethingRequired = getFromCache("key");
    std::optional<int> maybeInt = getFromCache<int,false>("anotherKey");
    return 0;
}
template<typename T,
         typename O = typename std::conditional_t<is_same_v<T, int>, int, optional<T>>>
O get(T in) {
    return {};
}

int main() {
    int seven = get(7);
    std::optional<std::string> maybeString = get("foo");
    return 0;
}