Search code examples
c++variadic-templatesvariadic

Passing const char* in variadic template argument list results in linker errors


I have following template class constructor for an exception class:

MyCustomException.h:

template<typename ... Args>
MyCustomException(const Message& msg, const char* fileName, int line, Args&& ... args);

MyCustomException.cpp:

template<typename ... Args>
MyCustomException(const Message& msg, const char* fileName, int line, Args&& ... args) {
  // random magic here
}

Now, when I am trying to pass it a const char* (e.g. in main.cpp):

#include "MyCustomException.h"

// ...

void myFunc() {

  try {
    // ...
    const Message m { id, msg };
    const char* mychar { "test string" };
  
    if (someCondition) {
      throw MyCustomException(m, __FILE__, __LINE__, mychar);
    }
  catch (MyCustomException& e) {
    // ...
  }
}

// ...

int main() {
  myFunc();
}

I keep getting a linker error LNK2019 (unresolved external symbol):

public: __cdecl MyCustomException::MyCustomException<char const *>(class Message const &,char const *,int,char const *)

When passing it a string literal, everything works just fine.

What's the deal with variadic template parameters and const char*?


Solution

  • The problem was with defining the template constructor inside a separate .cpp file. As G.M. linked to this post in the comments, template members should be implemented in the header file or, when defined in the .cpp file, at least be defined explicitly for each instance.