Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a class template member that belongs to all specializations

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...

like image 874
jpo234 Avatar asked Dec 18 '25 16:12

jpo234


1 Answers

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; };
like image 135
Caleth Avatar answered Dec 21 '25 06:12

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!