0

I tried making an extension to the built-in String class using C++/CLI, and using it from C++/CLI without success.

Here's the simplest I can boil it down to:

[System::Runtime::CompilerServices::Extension]
public ref class MyStringExtensions abstract sealed {
    public:        
        [System::Runtime::CompilerServices::Extension]
        static bool TestMethod(System::String^ str) { return false; }
};

Now, when I try to use this in other C++/CLI code, I get a compiler message indicating that TestMethod is not a method of String.

String^ foo = gcnew ...
...
blah = foo->TestMethod();  // compile-error

Any ideas?

jglouie
  • 12,523
  • 6
  • 48
  • 65
  • possible duplicate of [C++ Extension functions?](http://stackoverflow.com/questions/7922112/c-extension-functions) and http://stackoverflow.com/questions/2919715/is-there-such-a-thing-as-a-c-sharp-style-extension-method-in-c and http://stackoverflow.com/questions/5463009/extension-methods-in-c – Ben Voigt Mar 06 '12 at 23:53

1 Answers1

3

C++ doesn't have extension methods.

But it does have ADL (Argument-dependent lookup, also known as Koenig lookup) which is arguably even nicer.

svick
  • 236,525
  • 50
  • 385
  • 514
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • So this question http://stackoverflow.com/questions/6012578/how-can-i-create-net-extension-methods-by-c-cli is invalid? – jglouie Mar 07 '12 at 14:39
  • No, it's different. That one covers definition of extension methods in C++/CLI, not calling them from C++/CLI. C++/CLI doesn't know anything about extension methods (you can still use normal static method syntax), and the C++ idiom is to use an overloaded free function instead. – Ben Voigt Mar 07 '12 at 16:30