N + 4类型的C++模板专业化?

chr*_*irk 0 c++ templates struct pod specialization

我有一个类似的结构

template<typename T>
struct S
{
    T value;

    void Set(const T& val) { value = val; }

    void Foo();
}
Run Code Online (Sandbox Code Playgroud)

T可以是int,float,char,short和long long,也可以是N个其他基于struct的POD之一.

有大约50个左右的POD,它们看起来像:

struct POD1 { int i; char c; double d; }
struct POD2 { char c; double d; }
struct POD3 { POD1 p1; char s[10]; }
Run Code Online (Sandbox Code Playgroud)

我想知道如何最好地构建这种安排.如果我想要通用T案例来处理POD,我是否需要提供int,float,char,short和long long案例的明确,具体的定义?

先感谢您.

Ker*_* SB 6

首先,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);
  }
};
Run Code Online (Sandbox Code Playgroud)

(一些小问题:你可能想要callFoo私有化.也要考虑callFooconstness :如果适用,make 和Foo`不变.)