使用模板化类重载lexical_Cast
Overloading lexical_Cast with a templated class
我正在尝试扩展lexical_cast以处理字符串->cv::点转换,代码如下:
#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_cst函数。
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;
}
}
演示
前面的解决方案稍微复杂一点,如果你不喜欢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;
}
}
演示2
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符
- 重载Singly Linked List中的赋值运算符
- 取消引用运算符不能重载