使用依赖于模板参数的参数编写模板类的构造函数 [英] Writing constructor of template class with template argument-depending parameters
问题描述
请考虑以下两个带有构造函数的类,这些构造函数接受完全不同的参数集。
Consider the following two classes with constructors that accept wildly different sets of parameters.
class A {
public:
A(int x, double y) {
//do something
}
};
class B {
public:
B(const std::vector<bool>& x) {
//do something
}
};
现在,我想编写一个具有对象的类模板TpC(可能是A或B或其他)。换句话说,我希望能够使用以下内容:
Now, I want to write a class template TpC that will have an object (which might be A or B or something else). In other words, I want to be able to use the following:
int x;
double y;
std::vector<bool> z;
TpC<A> obj_a (x, y);
TpC<B> obj_b (z);
如何为TpC编写一个依赖于A和B的构造函数的构造函数?编写类似特征/策略的内容来告诉TpC每个特定专业化应使用的参数是可以接受的。
How can I write a constructor for TpC that is dependent on the parameters of the constructors of A and B? It would be acceptable to write something like a trait/policy to tell TpC what the parameters should be for each particular specialization.
推荐答案
您将需要使用模板构造函数。但是,为了防止调用此构造函数而不是复制构造函数,您需要添加一些歧义。例如:
You would need to use a template constructor. However, in order to prevent this constructor being called instead of the copy constructor, you need to add a bit of disambiguation. For example:
template<class T>
class TpC {
T t;
public:
struct in_place_t { };
static constexpr in_place_t in_place;
template<class... ARGS>
TpC(in_place_t, ARGS... args) : t(std::forward<ARGS>(args)...) {}
};
在C ++ 17中 in_place
可用在 std
中。
In C++17 in_place
is available in std
.
这篇关于使用依赖于模板参数的参数编写模板类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!