C++模板专用化,类作为返回类型,枚举作为参数

C++ Template specialization with class as return type and enum as parameter

本文关键字:返回类型 枚举 参数 C++ 专用      更新时间:2023-10-16

我没有太多使用模板的经验,但我正在尝试用一个返回不同类的函数基于枚举进行模板专门化。以下是示例代码(或者更确切地说,我正在努力实现的内容):

class Foo {
  // member variables
};
class Cat {
  // member variables
};
enum MyType{ A, B, C};
// Header file
template<class T, MyType U> std_shared_ptr<T> process();
// cpp file / implementation
template<> std_shared_ptr<Foo> process<Foo, A>()
{
}
template<> std_shared_ptr<Cat> process<Cat, C>();
{
}

有人能帮我弄清楚我在这里错过了什么或做错了什么吗?我试着搜索它,找到了一些处理枚举类型的解决方案(枚举的模板专用化),但是,我不知道如何将它与函数中的模板返回类型组合在一起。

编辑:我在这里尝试做的是基于枚举类型作为函数参数的模板专门化。同样的函数也返回一个模板类。因此,函数在这里有两个模板:T(返回参数)和U(输入参数,它是一个枚举)。有可能这样做吗?

编辑:修改了上面的示例以获得正确的行为。

不能部分专用化模板函数。

函数参数的值而不是类型不能更改返回值的类型。非类型模板参数的值可以更改返回值的类型,但返回值是在<>内传递的,必须在编译时确定,而不是在() s内。

标签可能会有所帮助。

template<MyType X>
using my_type_tag_t=std::integral_constant<MyType, X>;
template<MyType X>
constexpr my_type_tag_t<X> my_type_tag = {};
template<class T>struct tag_t{using type=T;};
template<class Tag>using type=typename Tag::type;
template<MyType>
struct my_type_map;
template<>
struct my_type_map<MyType::A>:tag<Foo>{};
template<>
struct my_type_map<MyType::B>:tag<Cat>{};

然后:

template<MyType X>
std::shared_ptr<type<my_type_map<X>>>
process( my_type_tag_t<X> );

您可以调用process( my_type_tag<A> )从中获取shared_ptr<Foo>

实现看起来像:

template<>
std::shared_ptr<Foo>
process( my_type_tag_t<MyType::A> ) {
  // blah
}

仍然不雅,可能无法解决您的问题,但它接近您描述的解决方案。