Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deprecate old name for class in C++

I work on a framework that has massively renamed all its classes and functions, I created a transition header allowing to use old names:

#define OldClassA NewClassA
#define OldClassB NewClassB
...

Now I would like the compiler to warn the user when the old name is used. How can I do this?

int main(){
  NewClassA newA;
  OldClassA oldA; // <-- This one would emit a warning
}
like image 969
azmeuk Avatar asked Jul 17 '13 09:07

azmeuk


3 Answers

As said by others, this is very compiler specific. Assuming your classes are defined with the new name. Here is what you can do with GCC and 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; } 

MSVC yields:

warning C4996: 'OldClassA': was declared deprecated

GCC yields:

warning: 'OldClassA' is deprecated

No warning is emmited for NewClassA newA; by either compiler.

like image 82
Cassio Neri Avatar answered Sep 30 '22 15:09

Cassio Neri


This is likely highly compiler specific.

For GCC, the reference page at http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Type-Attributes.html describes the deprecated attribute and has examples for typedefs which I think should suit your needs:

typedef NewClassA OldClassA __attribute__ ((deprecated));

Clang has somethign similar, see http://clang.llvm.org/docs/LanguageExtensions.html

For Visual C++, you could try its deprecated declaraton/pragma: http://msdn.microsoft.com/en-us/library/044swk7y(v=vs.80).aspx

like image 44
Tony Delroy Avatar answered Sep 30 '22 16:09

Tony Delroy


Since the release of C++14, you can now use the [[deprecated]] attribute, independent of the compiler (so long as the compiler fully supports C++14, of course).

In your case, you would use:

[[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;

Note that this is only supported in gcc-4.9 (if using gcc) and you will need to specify -std=c++1y. I do not know about MSVC; clang supports this as of version 3.4.

See http://josephmansfield.uk/articles/marking-deprecated-c++14.html for more details on how to deprecate things other than just typedefs.

like image 36
forkrul Avatar answered Sep 30 '22 16:09

forkrul