2013-02-06 68 views
1

在一個C++類中,我有一個全局布爾變量* const_var *在構造函數中設置,並在其他地方不變;而且有很多如果在我的課該變量條件,優化代碼,我想用模板ES:模板<布爾const_var>和實例對象與X <真>()全局布爾變量和模板

如何我可不可以做? 感謝的

這裏一個簡單的類沒有模板:

.h文件中

class X { 
public: 
bool const_var; 

X(bool b); 
void method1(); 

void method2(); 
void method3(); 
}; 

.cpp文件

X::X(bool b){ 
const_var=b; //unchanged elsewhere 
} 

void X::method1(){ 
... 
if(const_var==true) 
... 
if(const_var==false) 
... 
} 

void X::method2(){ 
... 
if(const_var==true) 
... 
if(const_var==true) 
... 
} 

void X::method3(){ 
... 
if(const_var==false) 
... 
if(const_var==true) 
    ... 
} 
+0

'const_var'根本不是全局的。 – MSalters

回答

0

您必須更改類定義爲類模板定義:

template <bool const_var> 
class X 
{ 
public: 
    X(); 
    void method1(); 
    void method2(); 
    void method3(); 
}; 

在實現中,你應該怎麼辦:

template <bool const_var> 
X<const_var>::X() {} 

template <bool const_var> 
X<const_var>::method1() 
{ 
    //... 
    if (const_var) 
    //... 
    if (!const_var) 
    //... 
} 

//dtto for method2 and method3 

if旨意被編譯器優化掉了。

但是,模板必須顯式實例化,或者它們的定義必須在使用它們的每個翻譯單元中可用。這意味着你必須要麼移動功能的軀體扔進頭文件,添加以下行到的.cpp:

template class X<true>; 
template class X<false>; 

還要注意,當你改變X成一個類模板,X將無更長一段時間;只有X<true>X<false>是類型。這意味着你不能,例如,聲明變量X x1(true);,它必須是例如X<true> x1;

+0

@MSalters感謝您的編輯。 – Angew

+1

一個也可以使用模板特給X ::方法1()根據const_var不同的功能體,它取決於代碼if語句編寫兩者共同的比率。 – odinthenerd

0

我不認爲模板最適用於此。你有一個假設是基於常量布爾值的2個不同事物的對象。你爲什麼不把X分解成2個不同的對象?

class Thing 
{ 
    public: 
     virtual ~Thing(){} 
     virtual method1() = 0; 
     virtual method2() = 0; 
     etc... 
}; 

class TrueThing : public Thing 
{ 
    virtual method1(){//performs true branch} 
    virtual method2(){//true branch} 
} 
class FalseThing : public Thing 
{ 
    virtual method1(){//performs false branch} 
    etc... 
} 

void main() 
{ 
    TrueThing true_thing; 
    FalseThing false_thing; 
    true_thing.method1(); 
    false_thing.method1(); 
} 
+0

這個問題的關鍵是引入優化,而不是虛擬調用的開銷。 – Angew