微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C如何区分容器模板和本机类型

我有以下问题:
template<class T>
void set(std::string path,const T data)
{
   stringstream ss;
   ss << data << std::endl;
   write(path,ss.str();
}

template<class T>
void set(std::string path,const T data)
{
    std::stringstream ss;
    for(typename T::const_iterator it = data.begin(); it < data.end(); ++it)
    {
       ss << *it;
       if(it < data.end() -1 )
          ss << ",";
    }
    ss << std::endl;
    write(path,ss.str());
}

我收到以下错误

error: ‘template<class T> void myclass::set(std::string,T)’ cannot be overloaded
error: with ‘template<class T> void myclass::set(std::string,T)’

有没有办法区分容器类型和模板中的其他类型?

解决方法

在C 03中,您可以使用一点SFINAE来执行此操作,以选择性地为不同类型启用不同版本的功能
#include <boost/type_traits.hpp>
#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

template<class T>
void set(typename boost::enable_if<boost::is_pod<T>,std::string>::type path,const T data)
{
   std::cout << "POD" << std::endl;
   stringstream ss;
   ss << data << std::endl;
}

template<class T>
void set(typename boost::disable_if<boost::is_pod<T>,const T data)
{
    std::cout << "Non-POD" << std::endl;
    std::stringstream ss;
    for(typename T::const_iterator it = data.begin(); it < data.end(); ++it)
    {
       ss << *it;
       if(it < data.end() -1 )
          ss << ",";
    }
    ss << std::endl;
}

int main() {
  int i;
  float f;
  std::vector<int> v;
  set("",v);
  set("",i);
  set("",f);
}

在这里使用了boost方便,但是如果不能选择boost或者使用C 11,你可以自己动手.

is_pod并不是你想要的,你可能想要一个is_container特性,但是that’s not so trivial,you’ll need to make a trait of your own和is_pod很好地近似了如何使用特征来选择性地启用函数作为简单的答案.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐