【问题标题】:Set template argument in other class in C++在 C++ 中的其他类中设置模板参数
【发布时间】:2017-02-04 11:36:02
【问题描述】:

有没有办法在另一个类中设置模板类的模板参数?我想要一个生成具有两个值的某种类型(正常、统一等)的分布的类。该类应该这样调用:

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&lt;Dist&gt;)。如果Dist 是模板类,我不能这样做。

【问题讨论】:

    标签: c++ class c++11 templates


    【解决方案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);
    

    【讨论】:

    • 谢谢!我编辑了我的问题。我希望现在更清楚我想要做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 2014-11-06
    • 2023-02-24
    • 2021-12-12
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多