首页 > 解决方案 > '尝试解析可变参数模板时无法推断出'T'的模板参数

问题描述

我正在尝试将结构类型列表传递给另一个类,该类将采用每个自定义类并将结构类型添加到包装器中并将其插入到元组中。一般来说,我是模板的新手,不知道为什么代码无法编译。

模板解析器包装器

namespace engine
{
    template<class T>
    struct component_manager
    {
        int component_id;

        std::vector<T> components;

        component_manager() : component_id(id_counter) { id_counter++; }
    };

    template<class... Ts>
    class ecs_manager
    {
    public:
        std::tuple<> components;
        
        template<class... Ts>
        ecs_manager()
        {
            constructor_helper<Ts...>();
        }

        template<class T, class... Ts>
        void constructor_helper()
        {
            components = std::tuple_cat(components, component_manager<T>());
            constructor_helper<Ts...>();
        }

        template<class T>
        void constructor_helper() {}
    };
}

结构

struct transform
{
    engine::vector3 position;
    engine::vector3 rotation;
    engine::vector3 scale;
};

struct motion
{
    engine::vector3 velocity;
};

struct mesh
{
    int id;
};

创建模板解析器包装器事物 engine::ecs_manager<transform, motion, mesh> ecs;

编译时,我得到这些: 无法推断' T'的模板参数没有找到匹配的重载函数

标签: c++templatesrecursionvariadic-templates

解决方案


不确定......但我想你正在寻找

template <typename ... Ts>
class ecs_manager
 {
   public:
      std::tuple<component_manager<Ts>...> components;
    
      ecs_manager () 
          : components{ component_manager<Ts>{} ... }
       { }
 };

无论如何... C++ 是一种强类型语言。

所以你不能定义一个空元组

std::tuple<> components;

并递归地递增它

components = std::tuple_cat(components, component_manager<T>());

您必须根据需要定义components并且不能更改它的类型运行时


推荐阅读