【发布时间】: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
}
【问题讨论】:
标签: c++ templates c++17 template-specialization