Home > Back-end >  extern c template instantiation
extern c template instantiation

Time:07-22

I want to write a templated function and explicitly instantiate it inside extern "C" block to avoid code duplication.

Here is example of what I mean:

template<typename T> // my templated function
T f(T val){
    return val;
}

extern "C"{
   int f_int(int val) = f<int>; // this does not compile, but this is what I want to achieve
}

CodePudding user response:

int f_int(int val) = f<int>; is not valid(legal) C syntax. The correct syntax to instantiate the function template and return the result of calling that instantiated function with val as argument would look something like:

template<typename T> // my templated function
T f(T val){
    return val;
}

extern "C"{
   int f_int(int val) {return f<int>(val);} // this does not compile, but this is what I want to achieve
}

Demo

  • Related