How can I provide template specializations for typedefs of the same type?

后端 未结 4 551
长情又很酷
长情又很酷 2021-01-20 02:49

A 3rd party SDK defines several typedefs, e.g.:

typedef unsigned char SDK_BYTE
typedef double SDK_DOUBLE
typedef unsigned char SDK_BOOLEAN

4条回答
  •  佛祖请我去吃肉
    2021-01-20 03:29

    You could do it like this:

    SDK_BYTE asByte(SdkVariant & var)
    {
      SDK_BYTE byte;
      bool const ok = var.toByte(byte);
      if (!ok) diePainfully();
      return byte;
    }
    
    SDK_DOUBLE asDouble(SdkVariant & var)
    {
      SDK_DOUBLE d;
      bool const ok = var.toDouble(d);
      if (!ok) diePainfully();
      return d;
    }
    
    SDK_BOOLEAN asBoolean(SdkVariant & var)
    {
      SDK_BOOLEAN b;
      bool const ok = var.toBool(b);
      if (!ok) diePainfully();
      return b;
    }
    
    static const bool byteAndBooleanAreTheSame = std::is_same::value;
    
    template 
    struct VariantCastImpl
    {
      template  T cast(SdkVariant & var) const;
    
      template <> SDK_DOUBLE cast(SdkVariant & var) const { return asDouble(var); }
      template <> SDK_BYTE cast(SdkVariant & var) const { return asByte(var); }
      template <> SDK_BOOLEAN cast(SdkVariant & var) const { return asBoolean(var); }
    };
    
    template <>
    struct VariantCastImpl
    {
      template  T cast(SdkVariant & var) const;
    
      template <> SDK_DOUBLE cast(SdkVariant & var) const { return asDouble(var); }
      template <> SDK_BYTE cast(SdkVariant & var) const
      {
        if (var.type() == SdkVariant::SdkByte)
        {
          return asByte(var);
        }
        else if (var.type() == SdkVariant::SdkBoolean)
        {
          return asBoolean(var);
        }
        else
        {
          diePainfully();
          return SDK_BYTE(); // dummy return, I assume diePainfully throws something
        }
      }
    };
    
    template 
    T variant_cast(SdkVariant & var)
    {
      return VariantCastImpl().cast(var);
    };
    

提交回复
热议问题