C++按类型组与基本类型组合的模板专用化
C++ template specialization by type groups combined with basic type
我想按类型组以及一些特定简单类型的额外定义来专门化模板。在 C++11 中并提升 1.60 可能吗?以下伪代码说明了我的意图:
template <typename T> // Universal definition
struct convert
{ ... }
template <> /* Definition for integral types like defined by std::type_traits */
struct convert<integral_types>
{ ... }
template <> /* Definition for floating point types like defined by type_traits */
struct convert<floating_types>
{ ... }
template <> /* Exception from integral types - specific definition */
struct convert<char>
{ ... }
我认为这可以通过标签调度程序解决,但我不确定这是否是最佳解决方案。另一种选择是enable_if
,结合is_integral
(和类似的组),但简单的char
类型是问题...
你可以做这样的事情:
template <typename T, typename Enabler = void> // Universal definition
struct convert
{ ... };
template <typename T> /* Definition for integral types like defined by std::type_traits */
struct convert<T, std::enable_if_t<std::is_integral<T>::value>>
{ ... };
template <> /* Exception from integral types - specific definition */
struct convert<char, void>
{ ... };
这是不使用std::enable_if_t
的替代解决方案:
// g++ -Wall -std=c++11 -o typetraitstest typetraitstest.C
#include <iostream>
#include <type_traits>
#include <cstdint>
template <typename T, bool isFloatingPoint, bool isSigned>
struct _Numeric;
template <typename T>
struct _Numeric<T, true, true>
{
void doit() { std::cout << "FloatingPoint " << sizeof (T) << " byten"; }
};
template <typename T>
struct _Numeric<T, false, true>
{
void doit() { std::cout << "SignedInt " << sizeof(T) << " byten"; }
};
template <typename T>
struct _Numeric<T, false, false>
{
void doit() { std::cout << "UnsignedInt " << sizeof(T) << " byten"; }
};
template <>
struct _Numeric<char, false, true>
{
void doit() { std::cout << "special case charn"; }
};
template <typename T>
struct Numeric :
_Numeric<T, std::is_floating_point<T>::value, std::is_signed<T>::value>
{};
int
main()
{
Numeric<float> f;
Numeric<int32_t> i32;
Numeric<uint64_t> u64;
Numeric<char> c;
f.doit();
i32.doit();
u64.doit();
c.doit();
return 0;
}
这是输出(请注意,char
似乎是签名的):
% ./typetraitstest
FloatingPoint 4 byte
SignedInt 4 byte
UnsignedInt 8 byte
special case char
相关文章:
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 为什么依赖模板类型在部分专用化中不可推导?
- 具有可变参数非类型参数的模板专用化
- 检查子类型时的专用方法模板
- 特定类型的模板函数的专用化
- 将"模板<类型名 T>zero()"扩展/专用为可调用的"T"
- 模板专用化和明确指定返回类型与自动
- 将返回类型专用化为 void 或 const 左值引用
- 专用于类型集的函数模板
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 为什么 std::optional::value_or 没有默认 ctor 类型的专用化?
- 具有模板专用化的泛型类型转换
- cpp 模板专用化,错误说参数 1 的类型为 T,这取决于参数 T
- 具有不同非类型模板参数的模板类部分专用化
- 从具有部分专用化的boost:hana::set中提取类型失败
- 带有void类型和参数的C++11模板专用化
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 如何为模板的内部类型专用化类
- 编译时的类型专用化