带有模板参数的构造函数
Constructor with template arguments
我有一个Dynamic
类可以存储不同的类型:int
、double
、std::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;
}
相关文章:
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在按值调用 (c++) 中转发构造函数参数
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 如何在构造函数参数中初始化"std::set"?
- 何时应在构造函数参数中使用 const C++?
- 使用模板化结构作为构造函数参数
- 使用 lambda 作为构造函数参数是否需要C++ 17?
- 如何使输入文本文件成为构造函数参数?c++
- shared_ptr构造函数参数是否应按值传递
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 复制构造函数参数为0
- 用作成员构造函数参数的函数的求值顺序
- 结构中的默认成员值或默认构造函数参数
- C++将引用成员绑定到构造函数参数
- 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?
- 模板函数指针参数与构造函数参数
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 如何基于构造函数参数模板化类成员函数的代码
- 将派生类构造函数参数传递给受保护的成员
- 如何根据构造函数参数使用超类类型初始化成员变量?