[英]Variadic template with class names
我有这个模板
template <typename T>
class Publisher
{
public:
Publisher(){}
~Publisher(){}
}
我有这个可变的模板
template <typename First, typename... Rest>
class PublisherContainer
{
PublisherContainer();
~PublisherContainer();
}
在PublisherContainer
构造函数中,我想为每个模板参数创建一个Publisher
:
template <typename First, typename... Rest>
PublisherContainer<First, Rest...>::PublisherContainer()
{
Publisher<First> publisher;
// create other publisher here.
}
所以我可以做
PublisherContainer<ClassA, ClassB, ClassC> myPublisher;
如何为每个模板参数调用Publisher
?
类模板不能具有“包成员”。 参数包必须转发或解包; 它们不能像类型一样使用。
最简单的答案是不要重新发明轮子,而是使用由紫色构建的产品类型std::tuple
:
template <typename ...Args>
struct PublisherContainer
{
std::tuple<Publisher<Args>...> publisher;
};
(请注意,“容器”可能是一个不好的名字,因为在标准C ++的惯用语中,容器是对元素的可迭代范围进行建模的对象。元组是一个产品(“每个”中的一个),而不是范围。也许是“ PublisherHolder” “是更合适的选择,或者完全删除包装层,而直接使用元组即可。)
Kerrek SB的回答是半正确的。 正确的是,您不能以当前尝试的方式打包成员,但是可以通过继承来实现。
首先,我们将定义一个基类:
template<typename T>
class PublisherBase{
public:
int some_member;
void some_method(){}
};
那么我们需要一个类来包含我们的基础:
template<typename T>
class Publisher{
public:
PublisherBase<T> self;
};
然后我们创建我们的容器或“容器”
template<typename First, typename ... Rest>
class PublisherContainer: public Publisher<First>, Publisher<Rest>...{};
我们可以这样使用:
int main(int argc, char *argv[]){
PublisherContainer<int, float, double, short> container;
container.Publisher<float>::self.some_method();
container.Publisher<short>::self.some_member = 5;
}
语法有点怪异,但是可以满足您的要求。 这种方法的唯一问题是,每种类型只能限制一个发布者。 但这可能也是理想的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.