如何模仿模板变量声明 [英] How to mimic template variable declaration

查看:155
本文介绍了如何模仿模板变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本类型 Item< N> ,它取决于整数模板参数 N 用于几个不同的 N Item 的实例

I have a basic type Item<N> which depends on an integer template parameter N and class Data which holds instances of Item<N> for several different N.

以下是一个示例:

template<unsigned N>
struct Item { ... }; // some template data type

struct Data
{
    std::set<Item<1>> items1;
    std::set<Item<2>> items2;
    std::set<Item<3>> items3;
    std::set<Item<4>> items4;
    std::set<Item<5>> items5;

    bool contains(const Item<1>& x) { return items1.find(x) != items1.end(); }
    bool contains(const Item<2>& x) { return items2.find(x) != items2.end(); }
    bool contains(const Item<3>& x) { return items3.find(x) != items3.end(); }
    bool contains(const Item<4>& x) { return items4.find(x) != items4.end(); }
    bool contains(const Item<5>& x) { return items5.find(x) != items5.end(); }
};

现在有了包含很多代码重复。是否有更优雅的方式来实现 Data

Now with several functions like contains there is a lot of code duplication. Is there a more elegant way to implement Data?

推荐答案

,例如,存储一个合适的 std :: tuple< ...> ,并让你的 contains()模板,例如:

You could, e.g., store a suitable std::tuple<...> and have your contain() function be a template, e.g.:

template <int... I>
struct DataImpl {
    std::tuple<std::set<Item<I>>...> data;
    template <int J>
    bool contains(Item<J> const& x) {
        return std::get<J-1>(data).find(x) != std::get<J-1>(data).end();
    }
};
using Data = DataImpl<1, 2, 3, 4, 5>;

这篇关于如何模仿模板变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆