Follow Slashdot stories on Twitter

 



Forgot your password?
typodupeerror
User Journal

Journal Journal: First Ever Type-Discriminant C++ Meta-Switch!

// the following is, i believe, the
// first example of a type-based
// meta-switch in C++.
// (note this is different to the
// static-int based switch in boost)

// also, i have bind1st, transform,
// find_if, remove_if, ... basically,
// i can do STL in meta-C++.

// full source if you ask.

// compiles and successfully passes on
// GCC 3.2.2

// Switch

template <class Discriminant, class Tuple_of_Cases, class Default>
struct Switch
{
    typedef bind1st_val<same_type_fun, Discriminant> pred;
    typedef typename find_if<Tuple_of_Cases, pred>::type found;
    typedef typename If<is_null<found>::val,
        Default, typename found::raw_type::second>::type type;
};

void test_switch()
{
    typedef Tuple<
        Pair<int, char>,
        Pair<char, float>,
        Pair<long, std::string>
        > Cases;
    typedef std::string Default;

    typedef Switch<int, Cases, Default>::type type0;
    typedef Switch<char, Cases, Default>::type type1;
    typedef Switch<long, Cases, Default>::type type2;
    //typedef Switch<short, Cases, Default>::type type3;

    assert(typeid(type0) == typeid(char));
    assert(typeid(type1) == typeid(float));
    assert(typeid(type2) == typeid(std::string));
    //assert(typeid(type3) == typeid(int));

    std::cout << "switch passed\n";
}

Slashdot Top Deals

An optimist believes we live in the best world possible; a pessimist fears this is true.

Working...