[英]C++ Template specialization with class as return type and enum as parameter
I don't have a lot of experience using templates but I'm trying to do template specialization based on enums with a function which returns different classes. 我没有使用模板的丰富经验,但是我试图基于枚举进行模板专门化,该枚举具有返回不同类的功能。 Below is the sample code (or rather what I'm trying to accomplish):
以下是示例代码(或更确切地说,我正在尝试完成):
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>();
{
}
Can someone help me in figuring out what I'm missing here or doing wrong? 有人可以帮助我弄清楚我在这里缺少什么或做错了吗? I tried searching it and found some solutions for handling enum types ( Template specialization for enum ), however, can't figure out how to put it together with a template return type in a function.
我尝试搜索它,发现了一些用于处理枚举类型的解决方案(enum的模板专业化 ),但是,无法弄清楚如何将其与函数中的模板返回类型放在一起。
EDIT: What I'm trying do here is to do template specialization based on enum type as argument to a function. 编辑:我想在这里做的是基于枚举类型作为函数的参数进行模板专门化。 And the same function returns a template class as well.
同样的函数也返回模板类。 So the function has two templates here: T (return param) and U (input param which is an enum).
因此,该函数在此处具有两个模板:T(返回参数)和U(输入参数,它是一个枚举)。 Is it possible to do so?
有可能这样做吗?
EDIT: Modified the above sample for the right behavior. 编辑:修改了上面的示例为正确的行为。
You cannot partially specialize template functions. 您不能部分专门化模板功能。
The value, not the type, of a function parameter cannot change the type of the return value. 函数参数的值而不是类型不能更改返回值的类型。 The value of a non-type template parameter can change the type of the return value, but that is passed within the
<>
and must be compile-time determined, not within the ()
s. 非类型模板参数的值可以更改返回值的类型,但是返回值的类型必须在
<>
内传递,并且必须在编译时确定,而不是()
内。
Tags may help. 标签可能会有所帮助。
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>{};
then: 然后:
template<MyType X>
std::shared_ptr<type<my_type_map<X>>>
process( my_type_tag_t<X> );
where you call process( my_type_tag<A> )
to get a shared_ptr<Foo>
out of it. 在其中调用
process( my_type_tag<A> )
以获得其中的shared_ptr<Foo>
的位置。
Implementations look like: 实现如下所示:
template<>
std::shared_ptr<Foo>
process( my_type_tag_t<MyType::A> ) {
// blah
}
still inelegant, and probably doesn't solve your problem, but it is close to your described solution. 仍然不够雅致,可能无法解决您的问题,但与您描述的解决方案很接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.