c++模板专门化N + 4种类型

C++ template specialization for N + 4 types?

本文关键字:4种 类型 专门化 c++      更新时间:2023-10-16

我有一个结构体

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 '保持不变。