Simple
Simple

Reputation: 14390

C language linkage typedef & templates

I understand that a template cannot appear inside an extern "C" block, the reason for which is that the name of the instantiated template functions cannot appear once than once using an unmangled name.

However, in the code below, the name of the function is being mangled (so there should be no problem because each instantiation will have a unique name) but still has function type with C language linkage. My question is whether the code below is well formed:

extern "C" using fn_type = void();

template<typename T>
fn_type foo;

int main()
{
    fn_type* const p = foo<int>;
    p();
}

Edit: it is hard to test if this is conforming just by running it through a compiler because GCC, Clang and MSVC don't distinguish between C++ and C function pointer types.

Upvotes: 1

Views: 564

Answers (1)

To me, the standard does not seem 100% clear on this. The only relevant part which mentions templates and linkage is C++11, [temp]§4:

A template name has linkage (3.5). A non-member function template can have internal linkage; any other template name shall have external linkage. Specializations (explicit or implicit) of a template that has internal linkage are distinct from all specializations in other translation units. A template, a template explicit specialization (14.7.3), and a class template partial specialization shall not have C linkage. Use of a linkage specification other than C or C++ with any of these constructs is conditionally-supported, with implementation-defined semantics. [...]

(Emphasis mine)

The paragraph starts with template names having linkage. Then it says "funciton template (notname) can have internal linkage; any other template name shall have external linkage."

To me, this seems to imply referring to the linkage of a template refers to the linkage of the template's name. If that interpretation is correct, then your example is well-formed, as the bolded part would apply to template names as well. Then nothing prevents function template types from having C linkage.

That's how I would interpret the standard.

Upvotes: 1

Related Questions