繁体   English   中英

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

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

我没有使用模板的丰富经验,但是我试图基于枚举进行模板专门化,该枚举具有返回不同类的功能。 以下是示例代码(或更确切地说,我正在尝试完成):

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>();
{
}

有人可以帮助我弄清楚我在这里缺少什么或做错了吗? 我尝试搜索它,发现了一些用于处理枚举类型的解决方案(enum的模板专业化 ),但是,无法弄清楚如何将其与函数中的模板返回类型放在一起。

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

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

您不能部分专门化模板功能。

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

标签可能会有所帮助。

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
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM