2014-10-09 28 views
1

我試圖延長lexical_cast的處理與字符串> CV ::點轉換,其代碼如下所示:重載lexical_cast的一個模板類

#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等。我無法找到將模板化參數暴露給lexical_cast,這樣我就可以擁有一個可處理所有cv::Point_<T>類型的lexical_cast函數。

回答

1
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

+0

那作品!雖然,我不確定那裏到底發生了什麼... – Yeraze 2014-10-09 18:30:57

+0

@Yeraze魔法模板專業化和SFINAE – 2014-10-09 18:32:17

+0

@Yeraze我簡化了一點 – 2014-10-09 18:39:14