2013-12-11 135 views
2

我的問題是關於變更/設定一個動態類型檢查的變量可以在運行時像這樣簡單的例子變化值的定義:運行時類型定義

void changeMode(int mode) 
{ 
    if(mode == 1) 
    { 
      typedef MyType float; 
    } 
    else if(mode == 2) 
    { 
      typedef MyType double; 
    } 
} 

int main(int argc, char *argv[]) 
{ 
    MyType (2); 
    MyType A = 3; 
    MyType B = 2; 
    MyType C = A + B; 

    return 0; 
} 

這是可能的?這是模板的經典案例?有可能避免使用模板?我的目標是集中化類型定義以便可以在運行時進行切換,而無需將其擴展到每個類,或者對將使用給定類型的每個類/函數使用「模板」。

+0

C++沒有任何類型的運行時類型系統(除了vtables)。這沒有任何意義。 – SLaks

回答

2

您可以提取您的類型相關的代碼函數模板(或類模板在更復雜的情況下):

template <typename MyType> 
void ExecuteTypeDependentCode() 
{ 
    MyType A = 3; 
    MyType B = 2; 
    MyType C = A + B; 
} 

然後,您可以但是,您可以使用polymorpic包裝類效仿這一行爲寫包裝,它的任務是模式之間切換:使用的

enum Modes 
{ 
    FloatMode = 1, 
    DoubleMode = 2 
}; 

void ExecuteTypeDependentCode(Modes mode) 
{ 
    switch (mode) 
    { 
     case FloatMode: 
      ExecuteTypeDependentCode<float>(); 
      break; 

     case DoubleMode: 
      ExecuteTypeDependentCode<double>(); 
      break; 
    } 
} 

實施例:

int main(int argc, char *argv[]) 
{ 
    ExecuteTypeDependentCode(DoubleMode); 

    return 0; 
} 

切換過程只能寫入一次(我描述過這種方法here)。

4

typedef在編譯時被評估,所以沒有。

,但你可以做這樣的事情使用prepocessor:

#ifdef TYPE_FLOAT 
    typedef float Type; 
#else 
    typedef int Type; 
#endif 

但請記住,這是在編譯時

1

Typedef是靜態評估,所以你需要做這樣的事情有一個「經典模板」(不管它是什麼:))

template <int Mode> 
struct Dispatch { }; 

template <> 
struct Dispatch <0> { 
    using U = int; // fancy way of saying typedef 
}; 

template <> 
struct Dispatch <1> { 
    using U = char; // feel free to use typedef 
}; 

int main() { 
    Dispatch<0>::U x; // compile time constant in <> (zero) 
    x = 5; 
    Dispatch<1>::U y; // compile time constant in <> (one) 
    y = 'c'; 
} 
0

至於其他的答案的情況下所指出的那樣,這是不可能通過實現。

#include <cstdio> 


class Gen 
{ 
public: 
    static int mode; 

    static Gen* get() 
    { 
     switch(mode) 
     { 
     case 1: 
      return new GenFloat(); 
     case 2: 
      return new GenDouble(); 
     } 

     return NULL; 
    } 
}; 

int Gen::mode = 0; 

class DoubleGen : public Gen 
{ 
public: 
    DoubleGen() : d(0) {} 
    DoubleGen(double val) : d(val) {} 

    double d; 
}; 

class FloatGen : public Gen 
{ 
public: 
    FloatGen() : f(0) {} 
    FloatGen(float val) : f(val) {} 

    float f; 
}; 




int main(void) 
{ 
    Gen::mode = 1; 

    Gen* _float = gen::get(); 

    gen::mode = 2; 

    Gen* _double = gen::get(); 

    delete _float; 
    delete _double; 

    return 0; 
}