浏览代码

common/bit_cast: Add function matching std::bit_cast without constexpr

Add a std::bit_cast-like function archiving the same runtime results as
the standard function, without compile time support.

This allows us to use bit_cast while we wait for compiler support, it
can be trivially replaced in the future.
ReinUsesLisp 5 年之前
父节点
当前提交
3f2e605dd1
共有 2 个文件被更改,包括 23 次插入0 次删除
  1. 1 0
      src/common/CMakeLists.txt
  2. 22 0
      src/common/bit_cast.h

+ 1 - 0
src/common/CMakeLists.txt

@@ -102,6 +102,7 @@ add_library(common STATIC
     atomic_ops.h
     detached_tasks.cpp
     detached_tasks.h
+    bit_cast.h
     bit_field.h
     bit_util.h
     cityhash.cpp

+ 22 - 0
src/common/bit_cast.h

@@ -0,0 +1,22 @@
+// Copyright 2020 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <cstring>
+#include <type_traits>
+
+namespace Common {
+
+template <typename To, typename From>
+[[nodiscard]] std::enable_if_t<sizeof(To) == sizeof(From) && std::is_trivially_copyable_v<From> &&
+                                   std::is_trivially_copyable_v<To>,
+                               To>
+BitCast(const From& src) noexcept {
+    To dst;
+    std::memcpy(&dst, &src, sizeof(To));
+    return dst;
+}
+
+} // namespace Common