xref: /aosp_15_r20/external/tensorflow/tensorflow/cc/experimental/libtf/impl/scalars.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_SCALARS_H_
16 #define TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_SCALARS_H_
17 
18 #include <stdint.h>
19 
20 #include <iosfwd>
21 #include <utility>
22 
23 namespace tf {
24 namespace libtf {
25 namespace impl {
26 
27 /** A thin wrapper around a C++ scalar value.
28  * This wrapper makes the scalar immutable.
29  */
30 template <typename T>
31 class Scalar final {
32  public:
Scalar(T x)33   explicit Scalar(T x) : value_(x) {}
Scalar(const Scalar<T> & o)34   Scalar(const Scalar<T>& o) : value_(o.value_) {}
35 
36   bool operator==(const Scalar<T>& o) const { return o.value_ == value_; }
37 
get()38   T get() const { return value_; }
39 
40   /** Absl hash function. */
41   template <typename H>
AbslHashValue(H h,const Scalar<T> & x)42   friend H AbslHashValue(H h, const Scalar<T>& x) {
43     return H::combine(std::move(h), x.value_);
44   }
45 
46  private:
47   const T value_;
48 };
49 
50 template <typename T>
51 inline std::ostream& operator<<(std::ostream& o, const Scalar<T>& x) {
52   return o << x.get();
53 }
54 
55 /** The overloaded addition operator. */
56 template <typename T1, typename T2>
57 inline auto operator+(const Scalar<T1>& x1, const Scalar<T2>& x2)
58     -> Scalar<decltype(x1.get() + x2.get())> {
59   using Ret = decltype(x1 + x2);  // Return type of this function.
60   return Ret(x1.get() + x2.get());
61 }
62 
63 using Int64 = Scalar<int64_t>;
64 using Float32 = Scalar<float>;
65 
66 }  // namespace impl
67 }  // namespace libtf
68 }  // namespace tf
69 
70 #endif  // TENSORFLOW_CC_EXPERIMENTAL_LIBTF_IMPL_SCALARS_H_
71