Home > OS >  Why does this c template need reference?
Why does this c template need reference?

Time:11-16

I try to print the type using specilization, but this doesn't work.

template<typename T>
struct print_type {
    static constexpr char const value[] = "unknown";
};

template<>
struct print_type<void> {
    static constexpr char const value[] = "void";
};

template<>
struct print_type<int> {
    static constexpr char const value[] = "int";
};

int main() {
    cout <<  print_type<void>::value << endl;
}

The compiler shows:

Undefined symbols for architecture x86_64:
  "print_type<void>::value", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64

I'm learning template, which confusing me for a long time, please help!!!

CodePudding user response:

Short answer: You need to activate C 17 or upgrade your compiler

Long answer: Even constexpr variables need a defenition. When you ODR-use a constexpr variable, you need to add the definition for it.

In C 17, constexpr variables part of a class-type definition are inline by default. Inline variable generate their definition like an inline function.

If you cannot have C 14, you need an out of line definition.

  • Related