data_type.h 2.3 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

#pragma once
#include <typeindex>
#include "paddle/framework/framework.pb.h"
Y
Yu Yang 已提交
18
#include "paddle/platform/enforce.h"
Y
Yu Yang 已提交
19 20 21 22 23 24 25 26 27 28 29

namespace paddle {
namespace framework {

inline DataType ToDataType(std::type_index type) {
  if (typeid(float).hash_code() == type.hash_code()) {
    return DataType::FP32;
  } else if (typeid(double).hash_code() == type.hash_code()) {
    return DataType::FP64;
  } else if (typeid(int).hash_code() == type.hash_code()) {
    return DataType::INT32;
30 31
  } else if (typeid(int64_t).hash_code() == type.hash_code()) {
    return DataType::INT64;
Y
Yang Yang(Tony) 已提交
32 33
  } else if (typeid(bool).hash_code() == type.hash_code()) {
    return DataType::BOOL;
Y
Yu Yang 已提交
34 35 36 37 38
  } else {
    PADDLE_THROW("Not supported");
  }
}

Y
Yu Yang 已提交
39 40 41 42 43 44 45 46 47 48
inline std::type_index ToTypeIndex(DataType type) {
  switch (type) {
    case DataType::FP32:
      return typeid(float);
    case DataType::FP64:
      return typeid(double);
    case DataType::INT32:
      return typeid(int);
    case DataType::INT64:
      return typeid(int64_t);
49 50
    case DataType::BOOL:
      return typeid(bool);
Y
Yu Yang 已提交
51 52 53 54 55
    default:
      PADDLE_THROW("Not support type %d", type);
  }
}

Y
Yu Yang 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
template <typename Visitor>
inline void VisitDataType(DataType type, Visitor visitor) {
  switch (type) {
    case DataType::FP32:
      visitor.template operator()<float>();
      break;
    case DataType::FP64:
      visitor.template operator()<double>();
      break;
    case DataType::INT32:
      visitor.template operator()<int>();
      break;
    case DataType::INT64:
      visitor.template operator()<int64_t>();
      break;
71 72 73
    case DataType::BOOL:
      visitor.template operator()<bool>();
      break;
Y
Yu Yang 已提交
74 75 76 77 78
    default:
      PADDLE_THROW("Not supported");
  }
}

Y
Yu Yang 已提交
79 80
}  // namespace framework
}  // namespace paddle