extern C 不能在类级别使用?

2023-12-03C/C++开发问题
33

本文介绍了extern C 不能在类级别使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

只是想确认在Windows环境下,VSTS 2008 + C++项目中,我们只能将extern C应用到函数级别,不能应用到类级别(所以类中的所有成员函数都使用C语言名称mangling)?试了好几种方法,总是编译错误.

Just want to confirm in Windows environment, VSTS 2008 + C++ project, we could only apply extern C to function level, not be able to apply to class level (so that all member functions from the class use C language name mangling)? I have tried several ways, but always compile error.

提前致谢,乔治

推荐答案

您可以通过一种非常复杂(但完全合法)的 hack 将 extern "C" 应用于成员函数:

You can sort of apply extern "C" to a member function via a very convoluted (but entirely legal) hack:

extern "C" typedef int bar_t(int x);

struct foo {
     bar_t bar; // yes, this declares a nonstatic member function!
};

int foo::bar(int x) { return x; } // definition

根据 ISO C++03 9.3[class.mfct]/9,这是可能的:

This is possible according to ISO C++03 9.3[class.mfct]/9:

可以使用函数类型的 typedef 声明(但未定义)成员函数.结果成员函数的类型与显式提供函数声明符时的类型完全相同,参见 8.3.5.

a member function can be declared (but not defined) using a typedef for a function type. The resulting member function has exactly the same type as it would have if the function declarator were provided explicitly, see 8.3.5.

然而,由于 ISO C++03 7.5[dcl.link]/4,这并没有真正给你带来任何好处:

However, this doesn't really buy you anything, because of ISO C++03 7.5[dcl.link]/4:

忽略类成员和成员函数的名称的 C 语言链接类成员函数的类型.

A C language linkage is ignored for the names of class members and the member function type of class member functions.

这篇关于extern C 不能在类级别使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6