1、Address of
怎么返回重載了 ampersand(&)符號(hào)的類的地址
// nonaddressable.h 定義了一個(gè)類,重載了C++的取地址運(yùn)算符(&)
class nonaddressable
{
public:
typedef double useless_type;
private:
useless_type operator&() const;
};
// addressof.cpp 實(shí)現(xiàn)代碼文件
#include "nonaddressable.h"
template <class T>
T * addressof(T & v)
{
return reinterpret_cast<T *>(&const_cast<char&>(reinterpret_cast<const volatile char &>(v)));
}
int main()
{
nonaddressable na;
nonaddressable * naptr = addressof(na); // No more compiler error. 這種方法可以取到這個(gè)類的地址
nonaddressable * naptr2 = &na; // Compiler error here. 常規(guī)方法會(huì)提示編譯錯(cuò)誤
return 0;
}
參開boost Boost addressof utility
以及 C++11 <memory> 文件
2、Boost mutant
Reverse a pair of plain old data (POD) types without physically reorganizing or copying the data items. 注釋:在C++中,我們把傳統(tǒng)的C風(fēng)格的struct叫做POD(Plain Old Data)對(duì)象。一般來說,POD對(duì)象應(yīng)該滿足如下特性。
對(duì)于任意的POD類型T,如果兩個(gè)T指針分別指向兩個(gè)不同的對(duì)象obj1和obj2,如果用memcpy庫函數(shù)把obj1的值復(fù)制到obj2,那么obj2將擁有與obj1相同的值。
簡(jiǎn)言之,針對(duì)POD對(duì)象,其二進(jìn)制內(nèi)容是可以隨便復(fù)制的,在任何地方,只要其二進(jìn)制內(nèi)容在,就能還原出正確無誤的POD對(duì)象。對(duì)于任何POD對(duì)象,都可以使用memset()函數(shù)或者其他類似的內(nèi)存初始化函數(shù)。
// 列子程序
#include <iostream>
template <typename T>
struct Reverse
{
typedef typename T::first_type second_type;
typedef typename T::second_type first_type;
second_type second;
first_type first;
};
template <typename T>
Reverse<T> & mutate(T & p)
{
return reinterpret_cast<Reverse<T> &>(p);
}
int main(void)
{
std::pair<double, int> p(1.34, 5);
std::cout << "p.first = " << p.first << ", p.second = " << p.second << std::endl;
std::cout << "mutate(p).first = " << mutate(p).first << ", mutate(p).second = " << mutate(p).second << std::endl;
return 0;
}
輸出結(jié)果
p.first = 1.34, p.second = 5
mutate(p).first = 5, mutate(p).second = 1.34
請(qǐng)按任意鍵繼續(xù). . .
|