C ++扩展功能? [英] C++ Extension functions?
问题描述
例如在C#中你可以这样做:
public static uint SwapEndian(this uint value)
{
var tmp = BitConverter.GetBytes(value);
Array.Reverse(tmp);
return BitConverter.ToUInt32(tmp,0);
}
someuint.SwapEndian();
在C ++中有什么类似的东西吗?
这不是C ++的做事方式。在C ++中,您可以使用命名空间,免费功能和 Koenig查询来扩展类的行为:
命名空间foo
{
struct bar {...}
void act_on_bar(const bar& b){...};
}
...
foo :: bar b;
act_on_bar(b); //不需要因为Koenig查找而限定
我通常认为扩展方法有害。如果你给一个类附加了太多的行为,你可能无法捕获类存在的原因。此外(像部分类),他们倾向于使与类非相关的代码非本地。
对于你的问题,在C ++中你只需:
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 swap(u.bytes [i],u.bytes [sizeof(T)-i - 1]);
return u.value;
}
用法:
swap_endian< std :: uint32_t>(42);
或者,如果可以推导出类型:
std :: uint64_t x = 42;
std :: uint64_t y = swap_endian(x);
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++?
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);
这篇关于C ++扩展功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!