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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With