c++ - 用模板类重载 lexical_Cast

标签 c++ templates lexical-cast

我正在尝试扩展 lexical_cast 以处理 string->cv::Point 转换,代码如下:

#include <iostream>
#include <opencv2/opencv.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

namespace boost {
  template<>
    cv::Point2f lexical_cast(const std::string &str) {
      std::vector<std::string> parts;
      boost::split(parts, str, boost::is_any_of(","));
      cv::Point2f R;
      R.x = boost::lexical_cast<float>(parts[0]);
      R.y = boost::lexical_cast<float>(parts[1]);
      return R;
    }
}

int main(int argc, char **argv) {
  auto p = boost::lexical_cast<cv::Point2f>(std::string("1,2"));
  std::cout << "p = " << p << std::endl;
  return 0;
}

而且效果很好.. 然而,cv::Point2f实际上是cv::Point_<T>其中 T 可以是 int、float、double 等。无论如何我找不到将模板化的 arg 公开给 lexical_cast,这样我就可以有一个 lexical_cast 函数来处理所有 cv::Point_<T>类型。

最佳答案

template <typename T>
struct point_type {};

template <typename T>
struct point_type<cv::Point_<T>> { using type = T; };

namespace boost {
  template <typename T, typename U = typename point_type<T>::type>
    T lexical_cast(const std::string &str)
    {
      std::vector<std::string> parts;
      boost::split(parts, str, boost::is_any_of(","));
      T R;
      R.x = boost::lexical_cast<U>(parts[0]);
      R.y = boost::lexical_cast<U>(parts[1]);
      return R;
    }
}

DEMO


如果您不喜欢 lexical_cast 的这个隐式第二个模板参数,则之前的解决方案稍微复杂一点:

#include <type_traits>

template <typename T>
struct is_point : std::false_type {};

template <typename T>
struct is_point<cv::Point_<T>> : std::true_type {};

template <typename T>
struct point_type;

template <typename T>
struct point_type<cv::Point_<T>> { using type = T; };

namespace boost {
  template <typename T>
    auto lexical_cast(const std::string &str)
      -> typename std::enable_if<is_point<T>::value, T>::type
    {
      std::vector<std::string> parts;
      boost::split(parts, str, boost::is_any_of(","));
      using U = typename point_type<T>::type;
      T R;
      R.x = boost::lexical_cast<U>(parts[0]);
      R.y = boost::lexical_cast<U>(parts[1]);
      return R;
    }
}

DEMO 2

关于c++ - 用模板类重载 lexical_Cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26285299/

相关文章:

c++ - boost::lexical_cast with boost::units::quantity 不再编译

c++ - C++ inFile.Read中大小后跟多个参数

c++ - 使用自定义Makefile而不是qmake交叉编译Ubuntu-Win7

c++ - 从类型包中解压缩模板-模板参数

c++ - 两种方式包含类和模板实例

c++ - 如何使用 boost lexical_cast 将字符串转换为 unsigned short?

c++ - 为什么书上说 “the compiler allocates space for variables in memory” ?

c++ - Qt 和 Q_OBJECT

c++ - 使用模板和继承的容器实现

c++ - boost::lexical_cast int 到用零填充的字符串