【问题标题】:How to deduce template return type with another template parameter with explicit specialization?如何使用具有显式特化的另一个模板参数推断模板返回类型?
【发布时间】:2021-05-13 13:50:38
【问题描述】:

我有一个具有以下签名的(成员)函数:

template<Type TypeToAllocate, typename Str>
    Str* allocate();

Type 是一个枚举,根据提供的枚举,我想返回 Str 类型的不同指针。

现在我不确定我该怎么做。示例代码在这里:

#include <functional>
#include <vector>
enum class Type {
    A,
    B
};

struct Bar{};
struct Baz{};

struct Foo {
    Type t;
    union {
        Bar b;
        Baz bz;
    };
};

struct Util {
std::vector<Foo> foos;

    template<Type TypeToAllocate, typename Str>
    Str* allocate();

};


template<>
    Bar* Util::allocate<Type::A>() {
        Foo& f = foos.emplace_back(Foo{});
        f.t = Type::A;
        f.b = Bar{};
        return &f.b;
    }

int main() {
    Util u{};
    Bar* b = u.allocate<Type::A>(); // this does not work
}

https://godbolt.org/z/T357KTnGd

【问题讨论】:

    标签: c++ templates c++17 template-specialization


    【解决方案1】:

    我不确定Str 在您的代码中的作用。如果这只是您尝试将枚举值映射到 BarBaz 的一部分,那么我认为您不需要它。

    我会使用一个特征,它可以很容易地专门用于 Type 的不同值:

    enum class Type {
        A,
        B
    };
    
    struct Bar{};
    struct Baz{};
    
    template <Type t> struct TypeMapper;
    template <> struct TypeMapper<Type::A> { using type = Bar; };
    template <> struct TypeMapper<Type::B> { using type = Baz; };
    
    template <Type t> using TypeMapper_t = TypeMapper<t>::type;
    
    struct Util {
        template<Type t>
        TypeMapper_t<t>* allocate() { 
            return new TypeMapper_t<t>();
        }
    };
    
    int main() {
        Util u{};
        Bar* b = u.allocate<Type::A>();
    }
    

    Live Demo

    我还建议你使用std::variant&lt;Bar,Baz&gt; 而不是联合。

    【讨论】:

    • 非常感谢。我在 msvc 中编译它时遇到了问题。我不得不把'typename'放在方法返回类型的前面。
    • @Raildex 是的,我的错。或者,您可以使用别名模板,请参阅编辑
    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 2021-05-29
    • 2021-12-09
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多