Joh*_*ith 5 c++ templates typedef function template-meta-programming
我希望typedef能够使用模板元编程作为函数选择器(如下例所示).我也尝试将函数作为模板参数传递.在这两种情况下都会出现错误,因为函数不是types.我知道如果它们是仿函数,这些方法中的任何一个都可以工作,但我希望能够有一个通用的解决方案.
是否有一种实际的" typedef功能"方式,但是在一个不同的名称下,我只是不知道?
编辑:
我此时的用例是我希望能够在使用boost::property_tree::xml_parser::read_xml和之间进行选择boost::property_tree::json_parser::read_json.但它不仅限于这种情况,并且使用成员函数,函数指针或std::function将要求找到并复制所有确切的函数定义以正确创建选择器.
描述用例的更一般方式就像使用一样,typedef double my_float以便稍后可以通过单个编辑来更改所有代码.或者,更高级,typedef可以在metaprogam选择器中定义.
void foo1() { /*do stuff*/ }
void foo2() { /*do other stuff*/ }
template <bool SELECT>
struct Selector {
typedef foo1 foo;
};
template <>
struct Selector<false> {
typedef foo2 foo;
};
Run Code Online (Sandbox Code Playgroud)
另外几个解决方案:
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();
Run Code Online (Sandbox Code Playgroud)
auto类模板的常量静态成员template <bool>
struct Selector
{
static constexpr auto foo = foo1;
};
template <>
struct Selector<false>
{
static constexpr auto foo = foo2;
};
// ...
Selector<true>::foo();
Selector<false>::foo();
Run Code Online (Sandbox Code Playgroud)
auto变量模板template <bool>
constexpr auto foo = nullptr;
template <>
constexpr auto foo<true> = foo1;
template <>
constexpr auto foo<false> = foo2;
// ...
foo<true>();
foo<false>();
Run Code Online (Sandbox Code Playgroud)