19

Are there extensions for C++ like there are in C#?

For example in C# you can do:

public static uint SwapEndian(this uint value)
{
    var tmp = BitConverter.GetBytes(value);
    Array.Reverse(tmp);
    return BitConverter.ToUInt32(tmp, 0);
}

someuint.SwapEndian();

Is there anything like that in C++?

2
  • 1
    No, C++ has nothing like this. AFAIK, there are no proposals for C++17 about it either (write one!). The D programming language has UFCS (uniform function call syntax), which is exactly "extension methods". It would be a nice feature to have since you could write non-member non-friend functions and avoid the object parameter, resulting in code that can be read left-to-right instead of "in-to-out/right-to-left".
    – gnzlbg
    Apr 8, 2014 at 23:05
  • 1
    This is one of many reasons why C++ can not be considered a valid programming language anymore. It's too outdated, lacks numerous features of modern languages like C#, and is the opposite of productive. Microsoft needs to start over again with a new compiled language that looks like C#/Java. If anyone tells me they use C++, I laugh at them and immediately see them as being less intelligent than myself.
    – Krythic
    Aug 7, 2016 at 17:50

7 Answers 7

8

There are no extension functions in C++. You can just define them as free functions.

uint SwapEndian(uint value){ ... }
1
  • This is the only response that uses the original code; thank you. It also shows an example of what is meant by free functions and most every other response here and elsewhere do not. Some responses in other threads related to this give a long philosophical description of OOP and how it is supposed to work but lack useful details.
    – Sam Hobbs
    Apr 12, 2018 at 18:15
6

Extension methods (and also "static classes") exist in C#/Java languages solely because the designers decided that (the Java way of) OOP is The One True Way and that everything must be a method from a class:

This is not C++ way of doing things. In C++ you have namespaces, free functions and Koenig lookup to extend the behavior of a class:

namespace foo
{
    struct bar { ... };

    void act_on_bar(const bar& b) { ... };
}

...

foo::bar b;
act_on_bar(b); // No need to qualify because of Koenig lookup

I usually consider extension methods harmful. If you attach too much behavior to a class, you are proabably failing to capture the reason why the class exists. Also (like "partial classes"), they tend to make the code related to a class non local. Which is bad.

As to your problem, in C++ you simply do:

template <typename T>
T swap_endian(T x)
{
    union { T value; char bytes[sizeof(T)]; } u;
    u.value = x;

    for (size_t i = 0; i < sizeof(T)/2; i++) 
        swap(u.bytes[i], u.bytes[sizeof(T) - i - 1]);

    return u.value;
}

Usage:

swap_endian<std::uint32_t>(42);

or, if the type can be deduced:

std::uint64_t x = 42;
std::uint64_t y = swap_endian(x);
3
  • 14
    Extension methods are just syntactic sugar.. you can have a free function act_on_bar and use it like act_on_bar(b) or b.act_on_bar(). The second way has nothing to do with the true OO way, only with readability. E.g. if you have 2 functions; act2(act1(b)) is less readable than b.act1().act2(). In C++ you have to make act1 and act2 member functions to get readable code, even when it would make more sense to have them as free functions! It would also improve generic programming too. And readable is not subjective here, since most people read text left to right, no in-to-out.
    – gnzlbg
    Apr 8, 2014 at 23:01
  • @gnzlbg, agreed. They were quite convenient in C# at times, however C# style extension methods always took this as non-const T& (reference). In the case of b(a) being equivalent to a.b(), would the first argument of b have to be a pointer or a reference? Would it ever make sense to copy? I would like this syntax to be available in C++ and wonder whether there are any barriers to it's introduction, other than disinterest from the community and committee. Oct 27, 2014 at 18:25
  • But surely the principle can be applied without classes at all. For raw C to bind functions to classes without forcing them into an ever-growing structure that is a class. I want C where I can bind functions to structures or primitives without any coupling nor uncontrolled mangling(since I bind myself, there is no mangling, since it gets translated at compile time). Free abstractions with zero abstraction leak into resulting binaries is beautiful.
    – Dmytro
    Apr 2, 2016 at 2:24
5

One method I have found is to use the overloaded ">>" operator with lambda expressions. The following code demonstrates this. You have to know to use operator ">>" instead of "->", this is because the compiler I use will not allow the operator "->" to be overloaded. Also because the operator ">>" has lower precedence than the "->" you have to use parentheses to force to compiler to evaluate the equation in the correct order.

In the end it becomes a matter of style, maintainability, reliability and cleanness of the code you are trying to produce. One would argue defining the "SubtractValue" method with two arguments creates more efficient code, but others would argue the overloaded method is more maintainable. In the end it is left to the architects and developers to determine what is important to their project. I am just providing a possible solution to the issue.

#include <functional>
#include <iostream>
#include <stdio.h>
#include <tchar.h>

// Some plain demo class that cannot be changed.
class DemoClass
{
public:
    int GetValue() { return _value; }
    int SetValue(int ivalue) { _value = ivalue; return _value; }
    DemoClass *AddValue(int iadd) { this->_value += iadd; return this; }

private:
    int _value = 0;
};

// Define Lambda expression type that takes and returns a reference to the object.
typedef std::function<DemoClass *(DemoClass *obj)> DemoClassExtension;

// Overload the ">>" operator because we cannot overload "->" to execute the extension.
DemoClass* operator>>(DemoClass *pobj, DemoClassExtension &method)
{
    return method(pobj);
}

// Typical extensions.

// Subtract value "isub".
DemoClassExtension SubtractValue(int isub)
{
    return [=](DemoClass *pobj) {
        pobj->AddValue(-isub);
        return pobj;
    };
}

// Multiply value "imult".
DemoClassExtension MultiplyValue(int imult)
{
    return [=](DemoClass *pobj) {
        pobj->SetValue(pobj->GetValue() * imult);
        return pobj;
    };
}

int _tmain(int argc, _TCHAR* argv[])
{
    DemoClass *pDemoObject = new DemoClass();
    int value = (pDemoObject->AddValue(14) >> SubtractValue(4) >> MultiplyValue(2))->GetValue();
    std::cout << "Value is " << value;
    return 0;
}

The above code output is "Value is 20".

3

Not like that, but you can write operator overloads which work on classes you didn't write, and it's a little like like method extensions (but not for named functions, only for operators that haven't been defined by that class already). The classic example is making your class work with cout:

class MyClass {
public:
    MyClass(const char* blah) : str(blah) { }

    const char* string() const {
        return str;
    }

private:
    const char* str;
};

// this is kinda like a method extension
ostream& operator<<(ostream& lhs, const MyClass& rhs) {
    lhs << rhs.string();
}

// then you can use it like this
MyClass m("hey ho");
cout << m;

// prints hey ho

This is a trivial example of course, but you get the idea.

2

Not in a directly-analogous way, but many times you can achieve the desired effect using templates. You cannot "add" methods to a concrete class in C++ without deriving from the original class, but you can create function templates that work with any type.

For example, here's a function template library I use to do ntoh-type conversions of any integral type:

template<class Val> inline Val ntohx(const Val& in)
{
    char out[sizeof(in)] = {0};
    for( size_t i = 0; i < sizeof(Val); ++i )
        out[i] = ((char*)&in)[sizeof(Val)-i-1];
    return *(reinterpret_cast<Val*>(out));
}

template<> inline unsigned char ntohx<unsigned char>(const unsigned char & v )
{
    return v;
}
template<> inline uint16_t ntohx<uint16_t>(const uint16_t & v)
{
    return ntohs(v);
}

template<> inline uint32_t ntohx<uint32_t>(const uint32_t & v)
{
    return ntohl(v);
}

template<> inline uint64_t ntohx<uint64_t>(const uint64_t & v)
{
    uint32_t ret [] =
    {
        ntohl(((const uint32_t*)&v)[1]),
        ntohl(((const uint32_t*)&v)[0])
    };
    return *((uint64_t*)&ret[0]);
}
template<> inline float ntohx<float>(const float& v)
{
    uint32_t const* cast = reinterpret_cast<uint32_t const*>(&v);
    uint32_t ret = ntohx(*cast);
    return *(reinterpret_cast<float*>(&ret));
};
3
  • This is quite a complex way to perform the task at hand. Oct 27, 2011 at 21:19
  • @Alexandre: It's the same as yours. The only difference is that I've provided specializations for built-in types that can be handled by ntohs and ntohl. Oct 27, 2011 at 21:23
  • in ntohx<uint64_t> how do you know the two 32-bit values in the return array are in the proper order? ;) Dec 1, 2014 at 9:37
1

If you're referring to the this-qualified method parameter, then no. But there may be some other clever tricks depending on your specific use case... Can you provide more detail?

0

No, sorry, but there's nothing like that in C++ and it can also never be. There are lots of things that the standard leaves as implementation-dependent (i.e. the compiler can do it any way it prefers), and also C++ does not have a standardized ABI.

4
  • 1
    I think to say "it can also never be" is a bit unreasonable. They could add some form of extension method mechanism if they wanted to, they've just chosen not to.
    – Sean
    Nov 26, 2013 at 13:49
  • 1
    @Sean: Extension methods would need to support this scenario: you take the headers of some third-party library A and your own code (library B) which defines and uses extension methods on the types defined in A. Your linker would then need to work out how to wire up the calls to a possibly prebuilt binary of A which can very well have been produced by a different compiler/linker. Unless there is standardization on an ABI (which is frankly not going to happen due to BC breaks) you cannot ever do that.
    – Jon
    Nov 27, 2013 at 10:50
  • @Sean: To put it another way: in .NET, assemblies are required to contain extremely detailed metadata on the types they contain. In C++ OTOH there is absolutely no guarantee that there is anything inside a binary to even hint that it contains some class you defined, never mind its name and other details.
    – Jon
    Nov 27, 2013 at 10:52
  • @jon an extension header would be compiled down to mangled free functions that take the object as the first argument. it's just syntactic sugar. nothing hard to implement at all. any abi compat issues you have with regular libraries would apply, sure... but not any worse. Apr 15, 2020 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.