azm*_*euk 21 c++ macros typedef deprecated c-preprocessor
我在一个大规模重命名所有类和函数的框架上工作,我创建了一个允许使用旧名称的转换头:
#define OldClassA NewClassA
#define OldClassB NewClassB
...
Run Code Online (Sandbox Code Playgroud)
现在我希望编译器在使用旧名称时警告用户.我怎样才能做到这一点?
int main(){
NewClassA newA;
OldClassA oldA; // <-- This one would emit a warning
}
Run Code Online (Sandbox Code Playgroud)
Cas*_*eri 25
正如其他人所说,这是特定于编译器的.假设您的类使用新名称定义.以下是GCC和MSVC可以做的事情:
class NewClassA {}; // Notice the use of the new name.
// Instead of a #define, use a typedef with a deprecated atribute:
// MSVC
typedef NewClassA __declspec(deprecated) OldClassA;
// GCC
//typedef NewClassA __attribute__((deprecated)) OldClassA;
int main(){
NewClassA newA;
OldClassA oldA;
}
Run Code Online (Sandbox Code Playgroud)
MSVC收益率:
警告C4996:'OldClassA':声明已弃用
GCC产量:
警告:'OldClassA'已弃用
NewClassA newA;两个编译器都没有发出任何警告.
这可能是高度编译器特定的.
对于GCC,http: //gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Type-Attributes.html上的参考页面描述了该deprecated属性,并提供了typedef我认为应该满足您需求的示例:
typedef NewClassA OldClassA __attribute__ ((deprecated));
Run Code Online (Sandbox Code Playgroud)
Clang有些类似,请参阅http://clang.llvm.org/docs/LanguageExtensions.html
对于Visual C++,您可以尝试使用它的deprecateddeclaraton/pragma:http://msdn.microsoft.com/en-us/library/044swk7y( v = vs.80).aspx
自从C++ 14发布以来,您现在可以[[deprecated]]独立于编译器使用该属性(当然,只要编译器完全支持C++ 14).
在您的情况下,您将使用:
[[deprecated]]
typedef NewClassA OldClassA;
// You can also include a message that will show up in the compiler
// warning if the old name is used:
[[deprecated("OldClassA is deprecated; use NewClassA instead.")]]
typedef NewClassA OldClassA;
Run Code Online (Sandbox Code Playgroud)
请注意,这仅在gcc-4.9中支持(如果使用gcc),您需要指定-std=c++1y.我不知道MSVC; clang从版本3.4开始支持此功能.
有关如何弃用除typedef之外的其他内容的更多详细信息,请参阅http://josephmansfield.uk/articles/marking-deprecated-c++14.html.