gpt4 book ai didi

c++ - 有没有办法在调用 boost::bind 对象时显式指定模板参数?

转载 作者:搜寻专家 更新时间:2023-10-31 02:14:46 25 4
gpt4 key购买 nike

我正在尝试为模板仿函数的特定实例创建一个通用的调度函数。在我的一些工作中,我有一个常见的模式,看起来像这样:

// func is some template function
char f;
if (f == 'B') return func<int8_t>();
else if (f == 'I') return func<int16_t>();
else if (f == 'L') return func<int32_t>();
// and so on

我想将这个通用逻辑包装到一个可重用的库中,该库将使用基于运行时值的特定模板参数调用给定函数。我不知道使用函数指针一般地执行此操作的好方法(因为你不能有指向模板的指针),但我想出了以下方法来使用通用仿函数类型 Func:

template <typename Func>
void format_dispatch(Func func, char f)
{
if (f == 'B') func.template operator()<int8_t>();
else if (f == 'I') func.template operator()<int16_t>();
else if (f == 'L') func.template operator()<int32_t>();
}

只要 Func 有一个采用单个模板类型参数的 operator(),我就希望上面的方法能够工作,它确实如此,就像下面的示例:

#include <iostream>
#include <stdint.h>
#include <typeinfo>

template <typename Func>
void format_dispatch(Func func, char f)
{
if (f == 'B') func.template operator()<int8_t>();
else if (f == 'I') func.template operator()<int16_t>();
else if (f == 'L') func.template operator()<int32_t>();
}

struct foo
{
template <typename T>
void operator()() const
{
std::cout << typeid(T).name() << std::endl;
}
};

int main()
{
format_dispatch(foo(), 'B');
format_dispatch(foo(), 'I');
}

虽然这有点限制。我希望能够传递绑定(bind)表达式来处理仿函数的调用运算符接受一些参数的情况,例如:

int x;
format_dispatch(boost::bind<void>(foo(), x));

但是,这不起作用,因为它看起来不像底层 bind_t 类型支持对其调用运算符的模板参数的显式规范。有什么方法可以完成我正在寻找的界面吗?对于这个应用程序,我无法利用 C++11;它只能是 C++03。

最佳答案

您可以创建自己的 boost::bind 类型。

template<typename F, typename T1>
struct TypedBind1 {
F f;
T1 t1;
template<typename T> void operator()() {
f.template operator()<T>(t1);
}
};

template<typename F, typename T1>
TypedBind1<F, T1> MakeTypedBind1(F f, T1 t1) {
TypedBind1<F, T1> result = { f, t1 };
return result;
};

示例用法:

struct bar {
template <typename T>
void operator()(int x) const {
std::cout << x << " " << typeid(T).name() << std::endl;
}
};

int main()
{
format_dispatch(foo(), 'B');
format_dispatch(foo(), 'I');
int x = 42;
format_dispatch(MakeTypedBind1(bar(), x), 'B');
format_dispatch(MakeTypedBind1(bar(), x), 'I');
}

如果没有 C++11 可变参数模板,您将不得不像 Boost.Bind 一样为每个您想要支持的参数重复此操作(或者可能使用 Boost.Preprocessor 或 Boost.MPL 魔法)。

关于c++ - 有没有办法在调用 boost::bind 对象时显式指定模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39538684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com