模板元編程-編譯期計算數值

來源:互聯網
上載者:User

比較早之前在論壇上看到一個文章,就是輸出-4在記憶體中的表示形式。
這是我寫的解答
還有個比較困難的問題,就是如何在編譯器拼出一個字串?反正我是想了很久都沒有不知道怎麼解決這個問題。
#include <cstdio>
#pragma pack( push )
#pragma pack( 1 )
template<int num ,int x>
struct data
{
    char c;
    enum { enumData = (x&0x80000000)?'1':'0'    };
    data< (num -1), (x<<1) > SubData;
    data():c(enumData){}
};
template<int x>
struct data<0,x>
{
    char c;
    data():c(0){}
};
#pragma pack( pop )
int main(int argc, char* argv[])
{
    data<32,-4> temp;
    printf("%s/n",&temp);
    return 0;
}

搞定了,最快的辦法
template<int n,int Num>
struct Bit
{
    enum{ Data= ((Num<<(n-1))&0x80000000)?'1':'0' };
};

char sz[]={
Bit<1 , -4>::Data,Bit<2 , -4>::Data,Bit<3 , -4>::Data,Bit<4 , -4>::Data,Bit<5 , -4>::Data,
Bit<6 , -4>::Data,Bit<7 , -4>::Data,Bit<8 , -4>::Data,Bit<9 , -4>::Data,Bit<10, -4>::Data,
Bit<11, -4>::Data,Bit<12, -4>::Data,Bit<13, -4>::Data,Bit<14, -4>::Data,Bit<15, -4>::Data,
Bit<16, -4>::Data,Bit<17, -4>::Data,Bit<18, -4>::Data,Bit<19, -4>::Data,Bit<20, -4>::Data,
Bit<21, -4>::Data,Bit<22, -4>::Data,Bit<23, -4>::Data,Bit<24, -4>::Data,Bit<25, -4>::Data,
Bit<26, -4>::Data,Bit<27, -4>::Data,Bit<28, -4>::Data,Bit<29, -4>::Data,Bit<30, -4>::Data,
Bit<31, -4>::Data,Bit<32, -4>::Data , 0 };

int main(int argc, char* argv[])
{
    printf("%s/n",sz);
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.