Search code examples
c++type-traitsstorage-class-specifier

Conditional storage class dependent upon template parameter


The following doesn't appear to be valid c++ (-std=c++2a). I want to change the storage class of var based on the template parameter b:

#include <type_traits>

template <bool b>
void f() {
  typename std::conditional<b, static int, int>::type var;
}

Solution

  • The storage class specifier is part of the object's declaration and is not part of the object's type.

    Hence it can't be used where a type is expected.

    Expanding on cigien's specialization proposal, you can wrap the variable into a helper container class.

    template<bool b> struct A;
    
    template<> struct A<true> {
        inline static int var = 0;
    };
    
    template<> struct A<false> {
        int var = 0;
    };
    
    template <bool b>
    void f() {
        A<b> a;
        int& var = a.var;
        do_something_with(var);
    }
    

    Beware that the semantics in doing this are quite different - one is created in automatic storage for every invocation, the other is initialized once and shared between invocations. In a threaded environment the former is safe, the latter isn't, etc.