欧美极品高清xxxxhd,国产日产欧美最新,无码AV国产东京热AV无码,国产精品人与动性XXX,国产传媒亚洲综合一区二区,四库影院永久国产精品,毛片免费免费高清视频,福利所导航夜趣136

標題: C++ Idioms [打印本頁]

作者: bibi    時間: 2015-4-18 20:14
標題: C++ Idioms
1、Address of

怎么返回重載了 ampersand(&)符號的類的地址

// nonaddressable.h 定義了一個類,重載了C++的取地址運算符(&)
class nonaddressable
{
public:
typedef double useless_type;
private:
useless_type operator&() const;
};

// addressof.cpp 實現代碼文件
#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. 這種方法可以取到這個類的地址

nonaddressable * naptr2 = &na;       // Compiler error here. 常規方法會提示編譯錯誤

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++中,我們把傳統的C風格的struct叫做POD(Plain Old Data)對象。一般來說,POD對象應該滿足如下特性。
   對于任意的POD類型T,如果兩個T指針分別指向兩個不同的對象obj1和obj2,如果用memcpy庫函數把obj1的值復制到obj2,那么obj2將擁有與obj1相同的值。

  簡言之,針對POD對象,其二進制內容是可以隨便復制的,在任何地方,只要其二進制內容在,就能還原出正確無誤的POD對象。對于任何POD對象,都可以使用memset()函數或者其他類似的內存初始化函數。





// 列子程序
#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;
}



輸出結果
p.first = 1.34, p.second = 5
mutate(p).first = 5, mutate(p).second = 1.34
請按任意鍵繼續. . .











歡迎光臨 (http://www.raoushi.com/bbs/) Powered by Discuz! X3.1