Use std::tuple for template parameter list instead of list of types

后端 未结 2 1942
梦谈多话
梦谈多话 2021-01-13 13:07

I\'m trying to make a call to a templated function like this :

typedef std::tuple Instrument         


        
2条回答
  •  死守一世寂寞
    2021-01-13 13:24

    Your first solution is failing because the second overload to get is not visible at the point of its own return type declaration; to get around this you would need to separate out the return type computation into its own subprogram.

    The second solution is closer; the problem is that you're only inferring the template std::tuple, not its arguments. An easy way to infer variadic arguments (e.g. type arguments to tuple) is through an empty tag structure, requiring one extra level of indirection:

    template struct type_tag {};
    
    class Cache {
        // ... (as above)
    
        template std::tuple get(type_tag>) {
            return get<0, Ts...>();
        }
    
    public:
        template T get() {
            return get(type_tag{});
        }
    };
    

    You should check to see whether you can write the solution using pack expansion instead of recursion, for example:

    template struct type_tag {};
    
    class Cache {
        template std::tuple get(type_tag>) {
            return std::tuple{Ts{}...};
        }
    
    public:
        template T get() {
            return get(type_tag{});
        }
    };
    

提交回复
热议问题