带有模板参数的构造函数

Constructor with template arguments

本文关键字:构造函数 参数      更新时间:2023-10-16

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

我希望我的动态类型有一个构造函数,我们在其中提供两个信息:

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

我期待着这样的事情

const Dynamic x<std::vector<double>>{10};

就地构造一个std::vector<double>长度为 10 的动态对象。

PS:我可以使用C++11,但我不能使用RTTI

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

#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 };
}

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

#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;
}