Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a scoped type as a macro name in C++?

Tags:

c++

macros

I would like to define a macro to accomplish the following:

#define std::vector Vector 

I can't do this because ":" seems to be not allowed in a macro name. The reason I want to do this is that I am trying to use Stroustrup's range-checked Vector (from std_lib_facilities.h in his book Programming Principles and Practice). He uses:

// disgusting macro hack to get a range checked vector:
#define vector Vector 

(the comment is Stoustrup's)

The problem is that I would prefer not to have "using namespace std;" in the header file that declares Vector. Which means that I need to use std::vector in other header files, and then Stroustrup's "macro hack" does not work. I get errors related to "std::Vector", which does not exist.

So my question is: is it possible to use a fully qualified type name as a macro name so as to replace it with something like "Vector"?

like image 371
freeze Avatar asked Dec 21 '25 15:12

freeze


1 Answers

Don't use the preprocessor. That's what alias templates are for:

template<typename T>
using vector_in_use = std::vector<T>;

You use vector_in_use throughout your code base, and it will compile your code with std::vector. Then, to switch you only need to replace one line:

using vector_in_use = Vector<T>;
like image 64
StoryTeller - Unslander Monica Avatar answered Dec 24 '25 10:12

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!