重载类型转换符

C++ 程序员都知道重载运算符:

   1: operator++

   2: operator==

   3: operator>>

比如C++ 中的输入输出:

   1: cout<<"Hello World!"<<endl;

   2: cin>>&value>>endl;

 

实际上就是重载了”>>” 和”<<”  运算法,但如果说重载类型转换符,可能不是所有的程序员都用到过,最近写一个配置文件的类就碰到了这样的问题。我希望使用 template<class T> T Config::string_to_T(const string& s) 函数返回指定类型的参数,T 类型由调用string_to_T() 的函数确定。比如:

   1: template<class T> T Config::Read(const string& key, const T& value)const{

   2:     ....from key we get value...

   3:     return string_to_T<T>(value);

   4: }

下面是我写的代码:

   1: template<class T> T Config::string_to_T(const string& s){

   2:     T t;

   3:  

   4:     istringstream ist(s);

   5:     ist >> t;

   6:  

   7:     return t;

   8: }

这段代码在大部分时候是没有问题的。

   1: int port

   2: port = Read("port", 0) \\返回了int 类型的端口号

   3: string ip

   4: Read("ip", ip)         \\返回了string 类型的ip 地址

但在T 类型为string 类型的时候,如果s 中包含了空格,那么返回的string 类型只包含了string value 的一部分。比如:

   1: str num_list

   2: port = Read("nums", num_list) \\num 如果对应的值是"1 2 3 4",那么则只返回 1

这是因为ist >> t 格式化输出到T t,当遇到有空格时会将string 分开输出。

解决方法也非常简单,就是的当类型为string 时直接返回,当不是string 类型时,通过上面的string_to_T() 方法即可,这就需要重载类型转换符,代码如下(operator std::string()const  和template<template T> operator T()const 分别重载了string() 和T() 类型转化符):

   1: class ToStringHelper

   2: {

   3:     std::string myValue;

   4: public:

   5:     ToStringHelper( std::string const& value )

   6:         : myValue( value )

   7:     {

   8:     }

   9:     operator std::string() const

  10:     {

  11:         return myValue;

  12:     }

  13:     template <typename T>

  14:     operator T() const

  15:     {

  16:         std::istringstream cvt( myValue );

  17:         T results;

  18:         cvt >> results;

  19:         //  Error checking here...

  20:         return results;

  21:     }

  22: };

  23:  

  24: ToStringHelper

  25: string_to_T( std::string const& s )

  26: {

  27:     return ToStringHelper( s );

  28: }

 

我的提问stackoverflow:http://stackoverflow.com/questions/13658667/how-can-i-return-a-string-as-a-template-class-in-c/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据