可变模板评估

时间:2016-01-11 16:31:52

标签: c++11 variadic-templates

我想知道是否可以将函数传递给可变参数模板以具有某种逻辑来启用或禁用特定参数。 让我解释一下。我在C ++ 11中有一个带有可变参数模板的实体 - 组件 - 系统系统,其中实体是简单的ID,组件是数据和/或小逻辑功能,所有逻辑都发生在系统内部。 系统使用可变参数模板获取所需的实体,其中包含具有特定组件列表的实体(我不使用id来检查组件),例如:

var entities = m_world.get<position, direction, acceleration>();

但我想知道它是否有可能做类似的事情:

var entities = m_world.get<position, direction, acceleration, Except<rotation, whatever>>();

过滤具有特定组件的实体。

我的ECS代码可在此处免费获取:https://github.com/arajar/ecs

感谢。

1 个答案:

答案 0 :(得分:0)

这很有可能。归档Search<Include<int, float>, Exclude<std::string, double>>::search();。您可以编写以下代码:

#include <tuple>
#include <typeinfo>
#include <iostream>

template<typename ...Args>
class Search;

template<>
class Search<std::tuple<>, std::tuple<>> {
public:
    static void search() {
    }
};

template<typename T, typename ...Include, typename ...Exclude>
class Search<std::tuple<T, Include...>, std::tuple<Exclude...>> {
public:
    static void search() {
        std::cout << "include: " << typeid(T).name() << std::endl;
        Search<std::tuple<Include...>, std::tuple<Exclude...>>::search();
    }
};

template<typename T, typename ...Exclude>
class Search<std::tuple<>, std::tuple<T, Exclude...>> {
public:
    static void search() {
        std::cout << "exclude: " << typeid(T).name() << std::endl;
        Search<std::tuple<>, std::tuple<Exclude...>>::search();
    }
};

template<typename ...Args>
using Include = std::tuple<Args...>;

template<typename ...Args>
using Exclude = std::tuple<Args...>;

int main() {
    Search<Include<int, float>, Exclude<std::string, double>>::search();
}