C++14以上 変数テンプレート

変数をテンプレートで書ける。 ありがちな使用例では、数値をそれぞれの型に、単純なキャストで変換するものが挙げられている。

template <class T>
constexpr T pi = static_cast<T>(3.14159265358979323846);

単純なキャスト以外で変数テンプレートを使うにはどうすればよいか。 lambda式とconstexpr if文の組み合わせ以外思いつかない。

#include <concepts>
#include <string>
#include <cassert>

template <typename T>
T v = []() {
    if constexpr (std::is_arithmetic_v<T>) {
        return 42;
    } else if constexpr(std::same_as<T, std::string>) {
        return "42";
    }
}();

int main() {
    auto i = v<int>;
    assert(i == 42);
    
    auto s = v<std::string>;
    assert(s == "42");
}

うーん、関数でよくない?