« Earlier6 items total Later »

Demangling C++ type information at run time

Here's a nice way to print the type of an object to an ostream. Handy during debugging when you have nested template horrors shriveling your brain.


#include <cxxabi.h>

template <typename T> struct TypeInfo {
    friend std::ostream &
        operator <<(std::ostream & os, TypeInfo<T> t){
            const std::type_info & ti = typeid(T);

            int status;
            char * realname = abi::__cxa_demangle(ti.name(), 0, 0, &status);
            os << realname;
            free(realname);
            return os;

        }
};


use as


std::cout << TypeInfo<std::vector<std::vector<int> > >() << std::endl


will print


std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >

Convert a string to anything using a function.

Not sure where this would be usefull but was playing around with the C++ cast operator and came up with this gem. Allows you to assign a string to any type in the declaration.

#!c++!#

int a = strconv("1");

struct strconv {
    std::string s;
    Convert(std::string s):s(s){

    }

    template <typename T> operator T ( ){
        std::istringstream ss(s);
        T t;
        ss >> t;
        return t;
    }

};

Syntax Highlighting For C++ Template Expansion Errors In Vim

Tired of looking at horrific unreadable template expansion errors when using c++. A little sprinkle of syntax highlighting makes the mess a little easier on the eyes.

Drop this snippet in your .vimrc

function! CppSyn()


    syntax cluster xOperators contains=xOperator1,xOperator2,xOperator3,xOperator4,xOperator5,xOperator6

    syntax region xBlock1 start=/\(\w\+\)\(::\w\+\)*</ end=/>/ contains=iBlock1
    syntax region iBlock1 start=/</ms=s+1 end=/>/me=e-1 contained containedin=xBlock1 contains=xBlock2

    syntax region xBlock2 start=/\(\w\+\)\(::\w\+\)*</ end=/>/ contains=iBlock2
    syntax region iBlock2 start=/</ms=s+1 end=/>/me=e-1 contained containedin=xBlock2 contains=xBlock1


    " ensure we don't match Foo::Bar::operator<< as the beginning of a
    " template
    syntax match xOperator1 "\(\w\+::\)*operator<<"

    " Create some sexy colors
    hi xBlock1 guifg=#44ff44
    hi xBlock2 guifg=#ff4444
    hi iBlock1 guifg=#4444ff
    hi iBlock2 guifg=#ff44ff

endf

au FileType qf call CppSyn()


Now run make from within VIM and your gcc/g++ error log will look like candy.

C++ foreach idiom

Isn't the STL wonderfull .... until you have started using languages such as Python and Ruby. In C++ to iterate over a STL container you have to write ick like this.


vector<int> v;
//Put some stuff in v

vector<int>::iterator it = v.begin();
for (;it != it.end(); it++ ){
   cout << *it;
}


Now I say that is clunky. STL iterator syntax is great when you want to do complex things but nasty when you want to do simple things. Have a look at this code which does exactly the same as the above code.


vector<int> v;
//Put some stuff in v

for(each<int> it; it.in(v);){
   cout << *it;
}


Much nicer. And here is the implementation of each. Obviously to achieve this magic you have some performance penalty as I need to take advantage of a class with virtual functions. Anybody who can see a way to improve this please contact me.


template <typename T> class iter{
public:
    virtual void inc() = 0;
    virtual T & operator*() = 0;
    virtual bool end() = 0;
    virtual ~iter() {

    }
};

template <typename T> class each{

    iter<T> * mIter;
    bool mIsEnd;
    T * mCurrent;

public:

    template <class C> class iterImpl : public iter<T> {
        typename C::iterator mIt;
        typename C::iterator mEnd;
    public:

        iterImpl(C & c):mIt(c.begin()), mEnd(c.end()){

        }
        void inc(){
            ++mIt;
        }
        T & operator*(){
            return *mIt;
        }
        bool end(){
            return mIt == mEnd;
        }
    };


    each(): mIter(NULL),mIsEnd(false),mCurrent(NULL)
    {
    }

    T & operator*(){
        return *mCurrent;
    }

    template <class C>bool in(C & container){
        if (mIter==NULL){
            mIter = new iterImpl<C>(container);
        }
        mCurrent = &**mIter;
        mIter->inc();
        if (mIsEnd){
            return false;
        }
        mIsEnd = (mIter->end());
        return true;
    }

};


Stripping constness using c++ templates

I've been working a lot with C++ in my new job. This means getting to grips once more with the STL, generic programming and templates. The more I dig into templates the more Alice In Wonderland it gets. We were playing around with a reference counting smart pointer. The basic template was ::


template <class ReferencePtr> class AutoPtr {
  ...
}


where ReferencePtr is the class of the pointer we wish to hold manage. For example


Foo * foo = new Foo;
AutoPtr<Foo> ptr = foo;


That was all well and good until we tried


const Foo * foo = new Foo;
AutoPtr<const Foo> ptr = foo;


This failed to compile. When we investigated we found parts of AutoPtr had declarations such as one of the constructors.


AutoPtr(const ReferencePtr * ref);


The problem with this is that if ReferencePtr is expanded as "const Foo" then the constructor expands to.


AutoPtr(const const Foo * ref);


which results in a compilation error. How to fix this? We need a const stripping template class to get to the raw type Foo without it's const. Here is a version


template <C> struct ConstStripper {
   typedef C type_name;
};
template <C> struct ConstStripper<const C> {
   typedef C type_name;
};


now we redefine our constructor as


AutoPtr(const typename ConstStripper<ReferencePtr>::type_name * ref);


now whether ReferencePtr is const Foo or just Foo const ConstStripper<ReferencePtr>::type_name will always expand to just Foo. Neat!

Now isn't that a constipated solution.




Text and Code Generation with Matlab

See MTemplate for the full tutorial and download.

This toolbox allows you to write hybrid text/matlab functions. This means you write text and embed matlab commands in the text to generate code, html, xml or any other general or specialized text formatted file.

For example the below file usecase1.mt

#% Example template.
#%
#% t = mtemplate_compile('mtemplate_usecase1.mt');
#% t(3)

# function usecase1(rows)
    <html>
        <body>
    # for i = 1:rows
        <tr><td>GEN_DATA = <%=gendata%></td></tr>
        <%=genline(i)%>
    # end
        </body>
    </html>
    # function gendata
        <%= i %>
    # end
#end

# function genline(row)
    <tr>
    #for e = 1:10
        <td> <%= e %> </td>
    #end
    </tr>
# end


when compiled and run as

t = mtemplate_compile('mtemplate_usecase1.mt');
t(3)


will generate


    <html>
        <body>
        <tr><td>GEN_DATA =         1 </td></tr>
            <tr>
        <td> 1 </td>
        <td> 2 </td>
        <td> 3 </td>
        <td> 4 </td>
        <td> 5 </td>
        <td> 6 </td>
        <td> 7 </td>
        <td> 8 </td>
        <td> 9 </td>
        <td> 10 </td>
    </tr>
        <tr><td>GEN_DATA =         2 </td></tr>
            <tr>
        <td> 1 </td>
        <td> 2 </td>
        <td> 3 </td>
        <td> 4 </td>
        <td> 5 </td>
        <td> 6 </td>
        <td> 7 </td>
        <td> 8 </td>
        <td> 9 </td>
        <td> 10 </td>
    </tr>
        <tr><td>GEN_DATA =         3 </td></tr>
            <tr>
        <td> 1 </td>
        <td> 2 </td>
        <td> 3 </td>
        <td> 4 </td>
        <td> 5 </td>
        <td> 6 </td>
        <td> 7 </td>
        <td> 8 </td>
        <td> 9 </td>
        <td> 10 </td>
    </tr>
        </body>
    </html>



It is also possible to generate XML / XHTML using the XML markup helper.

#% Example template.
#%
#%  This template uses the XML builder "xmlt"
#%
#% t = mtemplate_compile('mtemplate_usecase3.mt');
#% t()

#?CWS
# function mtemplate_usecase3
    # x = xmlt;

    #= x.html
        #= x.head
            <%= x.title('Hi There') %>
        #end
        #= x.body
            <%= x.h1('Heading 1') %>
            #= x.div('class', 'main_text')
                Here is a
                #= x.a('href', 'http://xtargets.com')
                    link
                #end
                to my homepage
            #end
            #= x.div('class', 'table_div')
               #= x.table
                    #= foreach(1:3) @(r)
                        #= x.tr
                            #= foreach(1:3) @(c)
                                #= x.td
                                    <%= r + c %>
                                #end
                            #end
                        #end
                    #end
               #end
            #end
        #end
    #end
# end


generates

<html>
<head><title>Hi There</title></head>
<body>
<h1>Heading 1</h1>
<div class = "main_text">
Here is a
<a href="http://xtargets.com">link</a>
to my homepage
</div>
<div class = "table_div">
<table>
<tr>
<td>2 </td>
<td>3 </td>
<td>4 </td>
</tr>
<tr>
<td>3 </td>
<td>4 </td>
<td>5 </td>
</tr>
<tr>
<td>4 </td>
<td>5 </td>
<td>6 </td>
</tr>
</table>
</div>
</body>
</html>



Goto downloads area

« Earlier6 items total Later »




Sponsored by

Sole Central

Your one stop shop for Birkenstock and Crocs shoes and sandles.