Is it possible to use template arguments in extern "C"' functions

Viewed 688

My requirement is to get an item from a collection using extern "c" function. The method will be as below

template<class _Ty,
class _Alloc = allocator<_Ty> >
extern "C" __declspec(dllexport) _Ty* __cdecl GetItem(std::vector<_Alloc>* itr, int index)
{
    if (itr->size() < index)
        return NULL;

    return &itr->at(index);
}

While compiling im getting an error as below

error C2988: unrecognizable template declaration/definition

The use of this extern method is to get object data using pinvoke from c#

3 Answers

No, that's not possible. The standard prohibits templates and their specialisations from having C linkage. Qutoing C++17 (N4659) [temp] 17/4:

... A template, a template explicit specialization (17.7.3), and a class template partial specialization shall not have C linkage. ...

Actually no, In mentioned template explicit specialization (17.7.3), and a class template partial specialization shall not have C linkage

I had a similar case where I had a header file that was included as exter "C" but I was able to define the template function withextern "C++". e.g.,

foo.c:

extern "C" {
#include "bar.h"
}

bar. h

...

extern "C++" template <typename T1, typename T2, typename T3>
static inline T1 __attribute__ ((always_inline))
f(T2 a, T3 b) {
  __builtin_unreachable();
}

extern "C++" template <>
static inline double __attribute__ ((always_inline))
f(int a, int b) {
   //
}

...

This worked with me in one particular situation: most but not all functions in bar.h needed to be included without demangling.

Related