Personal tools
You are here: Home → BCCS Blog → C++ Tips & Tricks
Navigation
Log in


Forgot your password?
 
Document Actions

C++ Tips & Tricks

Submitted by Jeremy Cook on 2006-06-30 19:39 — last modified 2006-07-13 10:29 —

Generic string conversion:

  std::string aDouble = toString(3.4);
  std::string aInt    = toString(4);

toString:

  #include <sstream>
  #include <iostream>

  //____________________________________________________ toString
  template <class T> 
  inline std::string toString(T x){
    std::stringstream ss;
    ss << x;
    return std::string(ss.str());
  }

Simple way to initialize a STL std::vector with arbitrary number of elements:

  static const std::vector<std::string>     
  months(Vector<std::string>("Jan")("Feb")("Mar")("Apr")("May")("Jun")("Jul")("Aug")("Sep")("oct")("Nov")("Dec"));

Vector class:

  template <typename T> class Vector;
  //________________________________________________________ VectorPacker
  template <typename T, unsigned int N>
  class VectorPacker{
    std::vector<T> & myVector;

    public:
    VectorPacker<T,N>(std::vector<T> & v):myVector(v){}

    VectorPacker<T,N+1> operator () (T elm) {
    if (myVector.size()>N)
      myVector.resize(N);
      myVector.push_back(elm);
      return VectorPacker<T,N+1>(myVector);
    }

    //operator const std::vector<T>& () const{return myVector;};
    operator std::vector<T> () {return myVector;};
    friend class VectorPacker<T,N-1>;
    friend class Vector<T>;
  };

  //________________________________________________________ Vector
  template <typename T>
  class Vector {
    std::vector<T> myVector;

    public:
    Vector(void){}
      explicit Vector(T elm) {
      myVector.push_back(elm);
    }

    //operator const std::vector<T>& () const {return myVector;};
    operator std::vector<T>(){return myVector;};

    VectorPacker<T,2> operator () (T elm){
      if (myVector.size()>1)
        myVector.resize(1);
        myVector.push_back(elm);
      return VectorPacker<T,2>(myVector);
    }
  }; 

BCCS Blog
« November 2007 »
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
BCCS Blog :
Partially closed site
C++ Tips & Tricks
Using structured text
How to add a news item
Adding group space
More...
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: