C++ 如何消除绑定表达式中的冗余类型说明符

C++ 如何消除绑定表达式中的冗余类型说明符,c++,templates,bind,C++,Templates,Bind,考虑以下代码: struct f{ void get(int a) {} }; struct g1{ template <typename Arg> void get(Arg a) {} }; struct g2{ template <typename... Args> void get(Args... args) {} }; int f2() { std::bind(&f::get,f(),2); // (A)

考虑以下代码:

struct f{
    void get(int a) {}
};
struct g1{
    template <typename Arg>
    void get(Arg a) {}
};
struct g2{
    template <typename... Args>
    void get(Args... args) {}
};

int f2()
{
    std::bind(&f::get,f(),2); // (A)
    std::bind(&g1::get<int>,g1(),2); // (B) redundant type specifier !
    //std::bind(&g1::get,g1(),2); // compiler error !
    std::bind(&g2::get<int, double>,g2(),2,1.1); // (C) redundant type specifiers !
    //std::bind(&g2::get,g2(),2,1.1); // compiler error !
    return 0;
}
struct f{
void get(int a){}
};
结构g1{
模板
void get(Arg a){}
};
结构g2{
模板
void get(Args…Args){}
};
int f2()
{
std::bind(&f::get,f(),2);/(A)
std::bind(&g1::get,g1(),2);/(B)冗余类型说明符!
//std::bind(&g1::get,g1(),2);//编译器错误!
std::bind(&g2::get,g2(),2,1.1);//(C)冗余类型说明符!
//std::bind(&g2::get,g2(),2,1.1);//编译器错误!
返回0;
}
在(B)和(C)的情况下,是否可以去掉冗余的模板参数? 我希望std::bind能够自动从其参数中扣除类型

我在想也许用可变模板参数和 decltype可能会隐藏此冗余类型规范


注意:我使用的是GCC4.4

我认为这在(成员)函数中是不可能的,因为
g1::get
g2::get
在可用之前必须用实际参数实例化

使用函数对象,您可以编写一个函数,该函数采用模板参数以及可变参数;然后,此函数可以使用您提供的参数实例化函数对象模板,并在绑定参数之前默认构造一个实例:

template <
    template <typename... Args> class VariadicFunc, 
    typename... ActualArgs >
auto mybind(ActualArgs... args)
    -> decltype(std::bind(VariadicFunc<ActualArgs...>(), args...))
{
    return std::bind(VariadicFunc<ActualArgs...>(), args...);
}

template <typename... Args>
struct functor
{
    void operator()(Args... args) {}
};

int main()
{
    mybind<functor>(1, 2); // instantiates a functor<int, int> and binds it
}
模板<
模板类VariadicFunc,
类型名。。。实际值>
自动mybind(实际值…参数)
->decltype(std::bind(VariadicFunc(),args…)
{
返回std::bind(VariadicFunc(),args…);
}
模板
结构函子
{
void运算符()(Args…Args){}
};
int main()
{
mybind(1,2);//实例化一个函子并绑定它
}
正如我前面所说的,这只适用于函数对象,而不适用于函数指针,因为不能使用模板函数指针参数化模板。

使用
操作符()
而不是
获取
方法。它将以这种方式工作:

#include <functional>
#include <iostream>

struct g1{
    typedef void result_type;
    template <typename Arg>
    result_type operator()(Arg a) {
        std::cout << "g1()" << std::endl;
    }
};
struct g2{
    typedef void result_type;
    template <typename... Args>
    result_type operator()(Args... args) {
        std::cout << "g2()" << std::endl;
    }
};

int main()
{
    std::bind(g1(),2)();
    std::bind(g2(),2,1.1)();
    return 0;
}
#包括
#包括
结构g1{
typedef void result_type;
模板
结果类型运算符()(参数a){

std::cout
std::bind
的第一个参数需要是一个完整的类型。我认为您无法摆脱