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;
};
Yet another couple of solutions:
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.
auto
member of a class templatetemplate <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.
auto
variable templatetemplate <bool>
constexpr auto foo = nullptr;
template <>
constexpr auto foo<true> = foo1;
template <>
constexpr auto foo<false> = foo2;
// ...
foo<true>();
foo<false>();
Live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With