c++模板专门化N + 4种类型
C++ template specialization for N + 4 types?
我有一个结构体
template<typename T>
struct S
{
T value;
void Set(const T& val) { value = val; }
void Foo();
}
T可以是int型、float型、char型、short型、long型或其他N个基于结构的pod之一。
大约有50个左右的pod,它们看起来像:
struct POD1 { int i; char c; double d; }
struct POD2 { char c; double d; }
struct POD3 { POD1 p1; char s[10]; }
我想知道如何最好地安排这个安排。如果我想用一般的T类型来处理pod,我是否需要为int、float、char、short和long long类型提供明确、具体的定义?
提前感谢。
首先,Set()
适用于任何基本类型、POD或聚合类类型,因为后一种类类型将有一个默认的赋值操作符。
唯一的问题是如何调用Foo()
。幸运的是,我们有类型特征来处理这个问题,即std::is_fundamental
。
#include <type_traits>
template <typename T> struct S
{
T val;
// Base case: call member `Foo()`.
template <typename U, bool Primitive, bool Array> struct callFoo
{
static void call(const U & u) { u.Foo(); }
};
// Specialization for primitive types (implement this yourself)
template <typename U> struct callFoo<U, true, false>
{
static void call(U u) { /* fundamental implementation here */ }
};
// Specialization for arrays: call `Foo()` on every element.
template <typename U> struct callFoo<U, false, true>
{
typedef typename std::remove_extent<U>::type V;
template <std::size_t N>
static void call(const V (&arr)[N])
{
for (std::size_t i = 0; i != N; ++i)
{
callFoo<V, std::is_fundamental<V>::value, std::is_array<V>::value>::call(arr[i]);
}
}
};
void Foo()
{
callFoo<T, std::is_fundamental<T>::value, std::is_array<T>::value>::call(val);
}
};
(一些小事情:您可能希望使callFoo
私有。同时也要考虑到一致性:如果可以的话,让callFoo
和Foo '保持不变。
相关文章:
- 在C++中,如何通过几种类型从元组中选择多个元素
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 在运行时检查继承是否只有一种类型和 void*
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- C++ 一个函数,可以根据接受的值返回两种类型之一
- C++指针中的这两种类型的值分配有什么区别?
- C++两种类型相互依赖
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 输出一个数字,该数字可能是三种类型之一
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- void* 数组将元素转换为另一种类型
- 将一种类型的比特重新解释为不同类型的比特的技术
- 两种类型的构造函数重载
- 没有使用两种类型的字符串进行匹配的函数调用
- 声明具有两种类型的变量:"int char"
- 使用每种类型的可变参数模板上的类模板初始化元组
- 是否可以在单行中获取第一种类型的参数包?
- 为什么需要类型名称,即使似乎足以推断名称应该是一种类型?
- 在 c++ 中将一种结构类型分配给另一种类型
- 将空基类优化对象强制转换为另一种类型是否会破坏严格的别名?