如何使用模板的C连接功能? [英] How to make a function with C-linkage from template?

查看:142
本文介绍了如何使用模板的C连接功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在看到答案后,我可能会迟到才知道这个标准陈述:

I may be a little late to know this standard statement, after seeing the SO answer:

[C ++ 11:7.5 / 1]

[C++11: 7.5/1]


具有不同语言链接的两种函数类型

Two function types with different language linkages are distinct types even if they are otherwise identical.

这意味着:

void f1();
extern "C" void f2();

decltype(f1) decltype(f2)

到目前为止我还不知道的原因是主要的编译器(例如g ++,clang,vc ++ ...)不遵守此规则。请参阅 LIVE DEMO

A reason that I wasn't aware of it until now is that the major compilers (e.g. g++, clang, vc++...) don't respect this rule. See LIVE DEMO.

但我相信大多数人(包括我)会对目前的不符合的行为感到满意。
如果编译器遵循标准,那么桥接C和C ++的许多代码就会被破坏。

But I believe most people (include me) will be happier with the current nonconformant behavior. If a compiler follows the standard, many codes that bridge C and C++ would be broken.

考虑这个例子:

库提供C API:

#ifdef __cplusplus
extern "C" {
#endif
void registerCallbackInC(void(*callback)(void*));
#ifdef __cplusplus
}
#endif

C ++中的库:

void f1(void*)
{
    ...
}

extern "C" void f2(void*)
{
    ...
}

registerCallbackInC(f1); // invalid, f1 has C++ linkage
registerCallbackInC(f2); // OK

要使用 registerCallbackInC callback 也必须有C连接,但是,我们不能使用 externC / p>

To use registerCallbackInC, the callback must have C-linkage as well, however, we can't use extern "C" with template:

extern "C"
{
    template<class T>
    void f(void*); // invalid
}

template<class T>
extern "C" void f2(void*); // invalid

template<class T>
struct F
{
    extern "C" static void f(void*); // invalid
};

这使得不可能使用模板合成C回调,我应该考虑这个需求是标准缺陷吗?

This makes it impossible to synthesize a C callback using template, should I consider the requirement a standard defect?

推荐答案

对模板的唯一限制是名称不能有C链接,它的类型没有限制,在模板的第一个声明中使用typedef作为C链接函数。

The only restriction on templates is that the name cannot have C linkage, there is no restriction on its type, so you can use a typedef for a C linkage function in the first declaration of the template.

extern "C" typedef void cfunc();
template <typename T> cfunc yourfunc;
template <typename T> void yourfunc() { }

这篇关于如何使用模板的C连接功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆