首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用模板化类重载lexical_Cast

用模板化类重载lexical_Cast
EN

Stack Overflow用户
提问于 2014-10-09 18:14:03
回答 1查看 223关注 0票数 1

我试图扩展lexical_cast以处理字符串->cv::Point转换,代码如下:

代码语言:javascript
复制
#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,这样我就可以有一个能够处理所有cv::Point_<T>类型的lexical_cast函数。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-09 18:26:51

代码语言:javascript
复制
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的第二个隐式模板参数

代码语言:javascript
复制
#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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26285299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档