extern c template instantiation

140 Views Asked by At

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
}
1

There are 1 best solutions below

0
user12002570 On BEST ANSWER

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