Home > Software engineering >  C : Declaring a template class member that belongs to all specializations
C : Declaring a template class member that belongs to all specializations

Time:09-22

What I'm looking for is a way to say: This is the same for all specializations:

template <typename T>
struct Foo {
  using id_type = unsigned int; // this does not depend on T!
};

Foo::id_type theId; // Doesn't matter what the specialization is, id_type is always the same.

I want to access id_type without having to specify the specialization...

CodePudding user response:

You can't have exactly what you are asking for. Foo is not a class. Foo<T> is a class, for any T.

You could have a non-template base that holds id_type

struct FooBase {
  using id_type = unsigned int;
};

template <typename T>
struct Foo : FooBase{};

FooBase::id_type theId;

You could provide a default parameter for T

template <typename T = struct FooPlaceholder>
struct Foo {
  using id_type = unsigned int; // this does not depend on T!
};

Foo<>::id_type theId;

However nothing stops me from writing an explicit specialisation of Foo that lacks (or redefines) id_type.

template <> struct Foo<MyType> { };    
template <> struct Foo<MyOtherType> { int id_type = 42; };
  • Related