C++ 在调用boost::bind对象时,是否有方法显式指定模板参数?

C++ 在调用boost::bind对象时,是否有方法显式指定模板参数?,c++,templates,boost,c++03,C++,Templates,Boost,C++03,我正在尝试创建一个通用分派函数,用于模板函子的特定实例化。在我的一些作品中,我有一个共同的模式,看起来像这样: // 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 o

我正在尝试创建一个通用分派函数,用于模板函子的特定实例化。在我的一些作品中,我有一个共同的模式,看起来像这样:

// 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
有一个
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');
}
#包括
#包括
#包括
模板
无效格式\u分派(Func Func,char f)
{
如果(f=='B')函数模板运算符();
else如果(f=='I')func.template运算符();
else如果(f=='L')func.template运算符();
}
结构foo
{
模板
void运算符()()常量
{

std::cout您可以创建自己的
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;
};
模板
结构类型bind1{
F;
T1;
模板无效运算符(){
f、 模板运算符()(t1);
}
};
模板
TypedBind1使TypedBind1(F F,T1 T1){
TypedBind1结果={f,t1};
返回结果;
};
示例用法:

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');
}
结构栏{
模板
void运算符()(int x)常量{
std::请按照此答案中的说明进行操作。
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');
}