1

I have a number of function pointers declared in a header file where the functions the pointers point to are assigned in a cpp file (depending on endianness).

For the non-template functions I just declare them as extern and everything works fine, like so:

parse.h

extern int32(*parseWord)(byte**);

parse.cpp

int32(*parseWord)(byte**) = IS_BIG_ENDIAN ? &pWordBE : &pWordLE;

For templated function pointers I assumed I could do the same:

parse.h

template<typename T>
extern T(*parse)(byte**);

parse.cpp

template<typename T>
T (*parse)(byte**) = IS_BIG_ENDIAN ? &pBE<T> : &pLE<T>;

But the above results in undefined references.

Is there a way of doing this kind of forward declaration?

chips
  • 160
  • 1
  • 10
  • Wouldn't it be simpler to use `template using parse = std::conditional_t), decltype(&pLE)>;` and put it in the header? – Henri Menke Jan 29 '20 at 03:11
  • I'm an old fashioned C guy and a lot of newer C++ stuff has passed me by so I'll have to research std::conditional<> and decltype - thanks for your input – chips Jan 29 '20 at 03:18
  • If you still want `parse` to be a value in a translation unit, you will have to use inline variables from C++17 and explicit instantiations. – Henri Menke Jan 29 '20 at 03:23
  • The reason why you are getting undefined references is ultimately that templates have to be implemented in the header file, see also https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – Henri Menke Jan 29 '20 at 03:25
  • I wanted to avoid that because apart from being a bit ugly (imo) it also seems a bit fragile – chips Jan 29 '20 at 03:26
  • Then you have to find out how to make `parse` *not* a template. – Henri Menke Jan 29 '20 at 03:28

0 Answers0