Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create "extension methods" like in C#, using macro in C++ ?

Tags:

c++

I would like to extend the std::string and to add "equals". So i did the following:

#define Equals(str1) compare(str1) == 0

and used the following code:

if ( str.Equals("hhhhllll") )

Which (i assume) compiles to

if ( str.compare("hhhhllll") == 0 )

And everything compiles great.

Now i want to improve my macro, add brackets to compile to

if ( (str.compare("hhhhllll") == 0) ) 

I've tried something like :

    #define (str).Equals(str1) (str.compare(str1) == 0)

But it won't compile (the macro simply doesn't fit)

How can i achieve it ?

like image 951
OopsUser Avatar asked Apr 05 '15 09:04

OopsUser


People also ask

Is it possible to add extension methods to an existing static class?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

Is it possible to achieve method extension using interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

Does C# have extension properties?

Add Extension Properties #5811C# already supports extension methods which allow for extending existing objects without altering the core contract/shape in any way, which provides a lot of benefit in when trying to add helper, convention, fluent style additions to a given type.


1 Answers

Your macro:

#define (str).Equals(str1) (str.compare(str1) == 0)

does not fit because it's not in line with macro definition. You can write something like this:

#define Equals(str, str1) (str.compare(str1) == 0)

but there is no need. All std::string instances can be compared with the overloaded operatror==.
So that you can write following code:

if (str == str1)

Using macro definition in C++ is highly unrecommended.

like image 93
agnor Avatar answered Oct 21 '22 14:10

agnor