The not any type

From codegorilla

Jump to: navigation, search

During my time I have found many things in boost that are exceptionally useful, one of these is the any type, that which can hold any other type.

However, I once had cause to have a type not be any-able (there is no point going into the reasons here, but it did happen and it was far to easy for a programmer to explicitly or implicitly place this type into an any).

So I came up with this technique to cause a compile time error if this type were ever placed in an any, basically it revolves around specializing the any::holder template class for our not any-able type. This still worked in boost 1.36.

Example

#include <boost/any.hpp>

class anything
{
    /* body ... */
};

// This is the type we don't want to be held in an any type
class not_any_able
{
    /* body ... */
};

namespace boost
{
    // we never want the not_any_able class being places inside a boost any
    // so we specialize the holder inside the any class.
    template<>
    class any::holder<not_any_able> : public any::placeholder
    {
        // No methods are supported - and do not add any
        // this is intentional, the type not_any_able is not allowed into
        // a boost::any
    };
}


int main(int argc, char* argv[])
{
    // we can place the type anything into an any, as we could any type
    boost::any does_compiler = anything();

    // but the following will cause a compile time error, as not_any_able
    // is not allowed to be an any
    boost::any does_not_compile = not_any_able();
    return 0;
}
Personal tools