C++11:仿函数的 return_type(对于 std::bind),其中返回类型基于输入类型

标签 c++ c++11 std boost-bind

我正在使用仿函数组合,其中仿函数的返回类型取决于输入类型:

template<typename V>
class F
{
protected:
    V v_;
public:
    using return_type = ?;

    F(V v) : v_(v) {}

    template<typename T>
    typename T::U operator()(T t)
    {
        v.method(t);
    }
};

...

X x;
Y y;
F<X> f(x);
F<Y> g(y);
auto h = std::bind(f, std::bind(g, _1));
h(...);  // problem is here :(

是否可以找到return_type使用decltype这样std::bind将工作?如果是这样,怎么办?

编辑:我替换 U<T>typename T::U因为返回类型取决于类型。我希望现在更清楚了。

编辑 2 (4?):添加了重现问题的可编译示例。

#include <functional>

using namespace std::placeholders;

template<typename I>
struct R
{
    using IT = I;
    R(I x, I y) : b(x), e(y) {}
    I b;
    I e;
};

template<typename IN, typename II>
class CI
{
    CI(II i) {}
};

template<typename IN>
class C
{
    template<typename IR>
    R<CI<IN, typename IR::IT> >
    operator()(IR& i)
    {
        return R<CI<IN, typename IR::IT> >(
            CI<IN, typename IR::IT>(i.b),
            CI<IN, typename IR::IT>(i.e));
    }
};

struct F {};
struct G {};
struct H {};

int main(int argc, char* argv[])
{
    C<F> a;
    C<G> b;
    auto c = std::bind(a, std::bind(b, _1));
    R<H> r{H{}, H{}};
    c(r);
}

最佳答案

暂时忘记使用 std::bind 并尝试直接方法:

C<F> a;
C<G> b;
R<H> r{H{}, H{}};
a(b(r));

这甚至无法编译,因此 bind 版本根本无法编译!

b(r) 由于访问冲突而无效,并且如果您修复 a(b(r)) 会失败,因为您尝试绑定(bind) a临时到非常量左值引用

关于C++11:仿函数的 return_type(对于 std::bind),其中返回类型基于输入类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383749/

相关文章:

c++ - 错误: ‘get_nprocs’ was not declared in this scope

c++ - 如何将子窗口的客户区保存到位图文件中?

c++ - 如何从qmake中的包含路径中删除项目的根目录

c++ - 每帧需要一次时 make_heap vs priority_queue 效率

c++ - 返回 C++ 中的映射以用作 lua 中的表

c++ - 外部图书馆

c++ - 为什么编译器将 float 的位数固定为6位?

c++ - 如何使用 std::bind 和 lambda

c++ - 使用可变参数模板的通用访问者

c++ - 指向不同返回类型和签名的函数的指针映射