在Bjarne Stroustrup的主页(C++ 11 FAQ)中:
struct X { int foo(int); };
std::function<int(X*, int)> f;
f = &X::foo; //pointer to member
X x;
int v = f(&x, 5); //call X::foo() for x with 5
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?std :: function如何调用foo成员函数?
模板参数int(X*, int)
,是&X::foo
从转换成员函数指针到一个非成员函数指针?!
(int(*)(X*, int))&X::foo //casting (int(X::*)(int) to (int(*)(X*, int))
Run Code Online (Sandbox Code Playgroud)
澄清:我知道我们不需要使用任何指针来使用std :: function,但我不知道std :: function的内部如何处理成员函数指针和非成员函数之间的这种不兼容性指针.我不知道标准如何允许我们实现像std :: function这样的东西!
假设我有float
IEEE 754 binary32的保证.给定一个与存储的有效浮点相对应的位模式std::uint32_t
,如何float
以最有效的标准兼容方式将其重新解释为?
float reinterpret_as_float(std::uint32_t ui) {
return /* apply sorcery to ui */;
}
Run Code Online (Sandbox Code Playgroud)
我有几种方法,我知道/怀疑/假设有一些问题:
通过reinterpret_cast
,
float reinterpret_as_float(std::uint32_t ui) {
return reinterpret_cast<float&>(ui);
}
Run Code Online (Sandbox Code Playgroud)
或者等价的
float reinterpret_as_float(std::uint32_t ui) {
return *reinterpret_cast<float*>(&ui);
}
Run Code Online (Sandbox Code Playgroud)
哪个遭受别名问题.
通过union
,
float reinterpret_as_float(std::uint32_t ui) {
union {
std::uint32_t ui;
float f;
} u = {ui};
return u.f;
}
Run Code Online (Sandbox Code Playgroud)
这实际上并不合法,因为它只允许从最近写的成员读取.然而,似乎有些编译器(gcc)允许这样做.
通过std::memcpy
,
float reinterpret_as_float(std::uint32_t ui) {
float f;
std::memcpy(&f, &ui, 4);
return f;
}
Run Code Online (Sandbox Code Playgroud)
哪种AFAIK是合法的,但复制单个单词的函数调用似乎很浪费,尽管它可能会被优化掉.
通过reinterpret_cast …
c++ standards-compliance type-conversion language-lawyer c++11