The Architect
The Architect

Reputation: 645

C++11 template definition in CPP file, undefined reference

I'm discovering some C++11 features and have a problem. I have a member function 'call'

class cscript
{
public:
template <typename ret_t, typename... params>
    bool call(ret_t &ret, const char * name, params... parameters);
....

Implementation:

template <typename ret_t, typename... params>
bool cscript::call(ret_t &ret, const char * name, params... parameters)
{
    ret_t (*func)(params...);
    func = (decltype(func)) tcc_get_symbol(tcc, name);
    if (!func)
        return true;

    ret = func(parameters...);

    return false;
}

When linking the following error is shown:

obj\Release\main.o:main.cpp:(.text.startup+0xcc)||undefined reference to `bool cscript::call<int, int, int>(int&, char const*, int, int)'|

Call example:

script.call(ret, "sum", 2, 3);

Any suggestions on how to make this work?

Upvotes: 2

Views: 4176

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

From the looks of it, the template definition isn't visible when it used. That is, the compiler has no idea what template parameters it needs to pass when it sees the implementation of cscript::call() and it has no idea how the implementation looks like when it is being used. You have two basic options:

  1. Put the definition of cscript::call() into the header so that it is always seen when it is used.
  2. Explicitly instantiate the versions of `csscript::call() you are using.

The latter would look something like below, somewhere after the definition in the implementation file:

template bool cscript::call<int, int, int>(int&, char const*, int, int);

From the looks of it you want to use several different versions of this template and you probably don't want to repeat things. Thus, it is likely that you want to put the definition into the header.

Upvotes: 5

Related Questions