Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typedef to rename functions

I would like to be able to typedef functions in order to be able to use template metaprogramming as a function selector (like in the example below). I've also tried passing the function as a template argument. In both cases the error arises because the functions are not types. I know either of these methods would work if they were functors, but I'd like to be able to have a general solution.

Is there an actual way to "typedef functions", but under a different name, that I'm just not aware of?

EDIT:

My use case at this time is that I would like to be able to select between using boost::property_tree::xml_parser::read_xml and boost::property_tree::json_parser::read_json . But it is not limited to just this case, and using member functions, function pointers or std::function will require all of the exact function defintions to be found and copied to correctly create a selector.

A more general way to describe the use case would be like using typedef double my_float so that at a later time all of the code can be changed with a single edit. Or, more advanced, the typedef could be defined in a metaprogam selector.

void foo1() { /*do stuff*/ }
void foo2() { /*do other stuff*/ }

template <bool SELECT>
struct Selector {
    typedef foo1 foo;
};

template <>
struct Selector<false> {
    typedef foo2 foo;
};
like image 477
John Smith Avatar asked Aug 15 '14 19:08

John Smith


1 Answers

Yet another couple of solutions:

1) C++03 solution: constant static function pointer as a member of a class template

typedef void (*Foo)();

template <bool>
struct Selector
{
    static const Foo foo;
};

template <bool select>
const Foo Selector<select>::foo = foo1;

template <>
const Foo Selector<false>::foo = foo2;

// ...

Selector<true>::foo();
Selector<false>::foo();

Live example.

2) C++11 solution: constant static auto member of a class template

template <bool>
struct Selector
{
    static constexpr auto foo = foo1;
};

template <>
struct Selector<false>
{
    static constexpr auto foo = foo2;
};

// ...

Selector<true>::foo();
Selector<false>::foo();

Live example.

3) C++14 solution: auto variable template

template <bool>
constexpr auto foo = nullptr;

template <>
constexpr auto foo<true> = foo1;

template <>
constexpr auto foo<false> = foo2;

// ...

foo<true>();
foo<false>();

Live example.

like image 87
Constructor Avatar answered Sep 22 '22 06:09

Constructor