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>();
{
}
有人能帮我弄清楚我在这里错过了什么或做错了什么吗?我试着搜索它,找到了一些处理枚举类型的解决方案(枚举的模板专用化),但是,我不知道如何将它与函数中的模板返回类型组合在一起。
编辑:我在这里尝试做的是基于枚举类型作为函数参数的模板专门化。同样的函数也返回一个模板类。因此,函数在这里有两个模板: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
}
仍然不雅,可能无法解决您的问题,但它接近您描述的解决方案。
相关文章:
- 无法将返回的枚举与枚举进行比较
- 在有符号基础类型枚举的位域上溢出
- 在编译时将强类型枚举器转换为其基础类型?
- 如果 int 是"not within the enums range",为什么将 int 转换为强类型枚举会编译?
- 一种创建将字符串常量返回给枚举的类的廉价方法,反之亦然
- 类型枚举的变量不是类型名称
- 强类型枚举的语法实现错误
- 枚举与强类型枚举
- 我可以编写一个在 c++ 中返回到枚举的函数吗?
- 错误:T没有命名类型-用于使用强类型枚举的专门化
- 如何使用强类型枚举
- QT:将强类型枚举参数传递到插槽
- 在类定义中声明类型(枚举、结构等)会增加代码大小
- 使用 SDL2 返回错误枚举值的函数
- Visual Studio 11 (beta) 中的强类型枚举类
- 使用强类型枚举对类型和子类型进行建模
- 不允许将强类型枚举用作同一基础类型的参数
- 如何正确使用C++强类型枚举
- 带有强类型枚举的模板参数推导
- 专用模板根据变量类型返回/设置枚举值