I have looked around all the related questions but no luck. Maybe this is a little bit strange use case hence no one really discussed before.
I have a specialized template struct "base". Then I try to use a template struct "derived" inherited the base and use the member of it.
The code:
template <typename T>
struct base {
char *type = "default";
};
// int base struct
template <>
struct base <int> { char *type="int"; };
// char base struct
template <>
struct base <char> { char *type="char"; };
// short base struct
template <>
struct base <short> { char *type="short"; };
template <typename T>
struct derived : base <T> {
char n0 = type[0]; // get the first char of "type" in base
};
int main (int argc, char** argv) {
struct derived<char> c_d;
cout << c_d.n0 << endl;
return 0;
}
The compilation error occurs
test.cpp:65:14: error: ‘type’ was not declared in this scope
char n0 = type[0];
^~~~
If I specialized the "derived" struct as well, it works.
template <typename T>
struct derived;
template <>
struct derived <int> : base<int> { char n0 = type[0]; };
template <>
struct derived <char> : base<char> { char n0 = type[0]; };
template <>
struct derived <short> : base<short> { char n0 = type[0]; };
However, It seems silly to repeat the same code in the derived struct. My questions are, why am I getting error and is there a better way to do it?
Thanks