带有模板参数的构造函数

时间:2018-01-23 15:47:27

标签: c++ c++11 templates constructor

我有一个Dynamic类,可以存储不同的类型:intdoublestd::vector<int>std::vector<double>等。我有大约50个这样的类类型。

我希望我的Dynamic类型有一个构造函数,我们给出两个信息:

  • 要存储的类型
  • 用于在Dynamic类
  • 中构造类型的参数

我期待像

这样的事情
const Dynamic x<std::vector<double>>{10};

构建一个长度为std::vector<double>的动态对象。

PS:我被允许使用C ++ 11,我不允许使用RTTI

2 个答案:

答案 0 :(得分:4)

必须推导构造函数模板参数。它们无法明确提供。您可以通过提供一个类型标记来解决这个问题,该标记对所需的模板参数进行编码并将其作为附加的构造函数参数传递。例如:

#include <utility>  // For std::forward

struct foo
{
    // Helper tag type
    template<class T>
    struct type_tag {};

    // The template argument T is deduced from type_tag<T>
    template<class T, class ... Args>
    foo(type_tag<T>, Args&&... p_args)
    {
        T value{ std::forward<Args>(p_args)... };
    }
};

int main()
{
    // Provide a type tag so the template argument can be deduced
    foo bar{ foo::type_tag<int>{}, 5 };
}

答案 1 :(得分:0)

只要您不介意将类型信息放在Dynamic旁边而不是变量名称,您就可以使用可变参数args执行此操作:

#include <iostream>
#include <vector>

template <typename T>
class Dynamic
{
public:
    template <typename... Args>
    Dynamic(Args... args) : data_(args...)
    {
    }

    T data_;
};

int main()
{
    const Dynamic<std::vector<double>> x{10};

    std::cout << x.data_.size() << std::endl;
}