2017-02-04 56 views
0

有沒有辦法在另一個類中設置模板類的模板參數?我想有一個類,它可以生成一個具有兩個值的特定類型(正常,統一等)的分佈。這個類應該被稱爲是這樣的:在C++的其他類中設置模板參數

Dist normal("normal",0,1) // this should construct std::normal_distribution<double> normal(0,1); 
Dist uniform("uniform",1,10); //std::uniform_real_distribution<double> uniform(1,10); 

的一種方法是使Dist類模板類爲好。但我想Dist是一個非模板類。原因是我有另一個類應該得到和作爲輸入Dist std :: vector(std::vector<Dist>)。如果Dist是模板類,我無法做到這一點。

回答

1

但我想知道是否有可能以上述方式做到這一點。

是的,但我不明白你爲什麼想這樣做。您需要使用某種運行時「字符串到工廠」地圖和類型擦除

struct VectorBase 
{ 
    virtual ~Vector() { } 

    // Common interface 
    virtual void something() { } 
}; 

template <typename T> 
struct VectorImpl : Vector 
{ 
    std::vector<T> _v; 

    // Implement common interface 
    void something() override { } 
}; 

struct Vector 
{ 
    std::unique_ptr<VectorBase> _v; 

    Vector(const std::string& type) 
    { 
     if(type == "int") 
      _v = std::make_unique<VectorImpl<int>>(); 
     else if(type == "double") 
      _v = std::make_unique<VectorImpl<double>>(); 
     else 
      // error 
    } 

    // Expose common interface... 
}; 

推薦/最佳方式是,正如你提到的,要Vector一個類模板

template <typename T> 
struct Vector 
{ 
    std::vector<T> _v; 

    template <typename... Ts> 
    Vector(Ts&&... xs) : _v{std::forward<Ts>(xs)...} { } 
}; 

用法:

Vector<int> IntVec(1, 2); 
Vector<double> DoubleVec(1.0, 2.0); 
+0

謝謝!我編輯了我的問題。我希望現在更清楚我想做什麼。 – beginneR

相關問題