c++ctemplatestemplate-function

Calling a template function from a C file


I know that templates are not defined in C. However in my case, i have an API written in C++, which is used by an application written in C. I wish to add a template function in the API. The function is defined as follows in abc.cpp:

template<typename T> T function_name(T param1){
  ...
  ...
  return val;
}

the declaration in abc.hpp as follows:

template<typename T> T function_name(T);

and this function is called from xyz.c as:

int a ,b = 5;
a = function_name(b);

However, it shows the following error in both abc.cpp and abc.hpp:

 error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token
 template<typename T>

Even using extern "C" doesn't help(leads to error: template with C linkage). My doubt is, is it even possible to call this template function in such a way? If yes, how can this be achieved? Thank you.


Solution

  • Since you mix C and C++ already (and therefore must have taken care of the possible issues), another solution is to continue developing the application in C++. That way new code can use all the nice features of the C++ library, like templates ;-), overloaded functions etc., and has access to C++'s standard library which can greatly enhance productivity.

    I don't see principal obstacles to using C++ for new source files in the application; whether it's easily possible and worthwhile to switch existing C files to C++ upon edits is another question.