I was searching for an implementation of extension methods in c++ and came upon this comp.std.c++ discussion which mentions that polymorphic_map can be used to
You can enable kinda extension methods for your own class/struct or for some specific type in some scope. See rough solution below.
class Extensible
{
public:
template
std::function operator|
(std::function& extension)
{
return [this, &extension](Args... args) -> TRes
{
return extension(*static_cast(this), std::forward(args)...);
};
}
};
Then inherit your class from this and use like
class SomeExtensible : public Extensible { /*...*/ };
std::function fn;
SomeExtensible se;
int i = (se | fn)(4);
Or you can declare this operator in cpp file or namespace.
//for std::string, for example
template
std::function operator|
(std::string& s, std::function& extension)
{
return [&s, &extension](Args... args) -> TRes
{
return extension(s, std::forward(args)...);
};
}
std::string s = "newStr";
std::function init = [](std::string& s) {
return s = "initialized";
};
(s | init)();
Or even wrap it in macro (I know, it's generally bad idea, nevertheless you can):
#define ENABLE_EXTENSIONS_FOR(x) \
template \
std::function operator| (x s, std::function& extension) \
{ \
return [&s, &extension](Args... args) -> TRes \
{ \
return extension(s, std::forward(args)...); \
}; \
}
ENABLE_EXTENSIONS_FOR(std::vector&);