模板元不定长参数递归展开

模板元递归展开

 template <typename T>
  void SetParams(const std::string& param_name, T&& param) {
    params_[param_name] = std::forward<T>(param);
  }

  /**
   * @brief Set params
   *
   * @tparam T Param type
   * @tparam Args Param_name:param values' type
   * @param param_name Unique param name
   * @param param Param value
   * @param args Param_name:param values
   */
  template <typename T, typename... Args>
  void SetParams(const std::string& param_name, T&& param, Args&&... args) {
    params_[param_name] = std::forward<T>(param);
    SetParams(std::forward<Args>(args)...);
  }

  /**
   * @brief Get param
   *
   * @tparam T Param type
   * @param param_name Param name
   * @return T Specified param
   */
  template <typename T>
  auto GetParam(const std::string& param_name) const -> typename std::remove_reference<T>::type {
    return any_cast<typename std::remove_reference<T>::type>(params_.at(param_name));
  }
template <class _ValueType>
_ValueType any_cast(any const & __v) {
  using _RawValueType = __uncvref_t<_ValueType>;
  static_assert(std::is_constructible<_ValueType, _RawValueType const &>::value,
                "ValueType is required to be a const lvalue reference "
                "or a CopyConstructible type");
  auto __tmp = any_cast<add_const_t<_RawValueType>>(&__v);
  if (__tmp == nullptr)
    throw bad_any_cast();
  return static_cast<_ValueType>(*__tmp);
}

template <class _ValueType>
_ValueType any_cast(any & __v) {
  using _RawValueType = __uncvref_t<_ValueType>;
  static_assert(std::is_constructible<_ValueType, _RawValueType &>::value,
                "ValueType is required to be an lvalue reference "
                "or a CopyConstructible type");
  auto __tmp = any_cast<_RawValueType>(&__v);
  if (__tmp == nullptr)
    throw bad_any_cast();
  return static_cast<_ValueType>(*__tmp);
}

template <class _ValueType>
_ValueType any_cast(any && __v) {
  using _RawValueType = __uncvref_t<_ValueType>;
  static_assert(std::is_constructible<_ValueType, _RawValueType>::value,
                "ValueType is required to be an rvalue reference "
                "or a CopyConstructible type");
  auto __tmp = any_cast<_RawValueType>(&__v);
  if (__tmp == nullptr)
    throw bad_any_cast();
  return static_cast<_ValueType>(std::move(*__tmp));
}

template <class _ValueType>
add_pointer_t<add_const_t<_ValueType>> any_cast(any const * __any) {
  static_assert(!std::is_reference<_ValueType>::value,
                "_ValueType may not be a reference.");
  return any_cast<_ValueType>(const_cast<any *>(__any));
}
posted @ 2021-06-11 17:12  cyssmile  阅读(57)  评论(0)    收藏  举报