2017-02-04 54 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

相关问题