考虑参考和const的可变函数包装器

gra

我创建了一个小的函数包装器示例。我想让包装器考虑调用的函数是否使用(const)引用,这意味着输出将是4/5而不是4/4,但是如果包装的函数没有使用,我不想强​​制引用使用它们。

#include <iostream>
#include <string>

struct a {
  static void run(int cref) {
    cref = 5;
  };
};

struct b {
  static void run(int &cref) {
    cref = 5;
  };
};

template <class FTor>
struct foo {
    template <class ... Args>
    static void wrapper(Args ... args) {
      FTor::run(args ...);
    }
};


int main()
{
    int bar = 4;
    foo<a>::wrapper(bar);
    std::cout << bar;

    foo<b>::wrapper(bar);
    std::cout << bar;
}
爵士先生

仅使用完美转发该怎么办?

template <class FTor>
struct foo {
    template <class ... Args>
    static void wrapper(Args && ... args) {
      FTor::run(std::forward<Args>(args) ...);
    }
};

这样,无论参数对输入具有什么ref限定,都将传递给内部函数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章