可以创建匹配枚举类型的类模板的部分模板特化吗?
Can I create a partial template specialization of of a class template matching enumeration types?
我有一个函数模板,由一组类模板显式特化提供语法,如
abc.GetAs<DesiredType>("Name");
(其中GetAs<t>
类似于:
template<typename T>
T GetAs(wchar_t const* propName) const
{
typedef Converter<T> Converter;
auto thing = Get(propName);
return Converter::Convert(thing);
}
)
我想对DesiredType
进行专门化,当该类型是枚举时,以便返回类型与枚举(或enum class
)的底层类型匹配。
这是可能的吗?还是客户端只需要自己指定底层类型?
我试图允许这样的代码:
enum class Example
{
One,
Two
}
int main()
{
foo_ipc_class ic(L"/// Construct me");
// Today, calls the primary template rather than an explicit
// specialization for an integral type.
Example ex = ic.GetAs<Example>(L"Property Name");
}
由于不可能部分专门化函数模板,因此您必须更改实现以使用"委托到类"技巧:
#include <type_traits>
// Class to delegate to
template <typename T, bool isEnum = std::is_enum<T>::value>
struct GetAs_Class {
typedef your_return_type ReturnType;
static ReturnType GetAs(your_parameters) { your_code; }
};
// Partial specialisation
template <typename T>
struct GetAs_Class<T, true> {
typedef specialisation_return_type ReturnType;
static ReturnType GetAs(your_parameters) { specialisation_code; }
};
// Your function now delegates to the class
template <typename T>
typename GetAs_Class<T>::ReturnType GetAs(your_parameters) {
return GetAs_Class<T>::GetAs(your_arguments);
}
您可以使用SFINAE基于模板参数是否是enum来启用/禁用重载。std::is_enum
和std::underlying_type
很方便。为了简单起见,我把GetAs
写成一个自由函数:
#include <type_traits>
#include <iostream>
template<typename T>
struct identity {
typedef T type;
};
template<typename T>
typename std::enable_if<!std::is_enum<T>::value, identity<T>>::type::type
GetAs(wchar_t const*)
{
std::cout << "generaln";
// return something
}
template<typename T>
typename std::enable_if<std::is_enum<T>::value, std::underlying_type<T>>::type::type
GetAs(wchar_t const*)
{
std::cout << "enumn";
// return something
}
enum class E : short {
};
int main()
{
GetAs<int>(L"hm");
GetAs<E>(L"hm");
}
这很难看,但是委托给一个类来模仿函数模板的部分专门化也是如此,IMO:)
相关文章:
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 如何在C++中创建类型列表的 n 路笛卡尔积?
- 使用 C++17,如何创建类型到值的编译时图?
- C++ 中的对象创建类型有什么区别?
- 在 C++ 中创建类型向量
- 创建类型列表并访问每种类型的静态成员?
- 无法创建类型为无序链接列表的对象
- 如何为指针创建类型定义
- 在没有宏的情况下在 C++98 中创建类型列表时遇到问题
- 使用特定成员变量值创建类型的类型
- <T> 从类型对象创建类型<T1>对象的构造函数
- 创建类型结构的指针阵列
- C++当类型T需要构造函数时,是否可以创建类型T的std::列表
- 在C++中创建类型定义
- 是否可以在 c++ 中创建类型的向量
- 创建类型为 'this'/当前对象的指针
- 如果模板化"ResourceCache"需要不同的创建参数/方法,它们如何加载/创建 T 类型的资源?
- ptr_fun - 无法创建类型?
- 如何从继承的自定义类 c++ 创建类型
- DLL 创建类型