C++:将成员变量的引用/指针作为模板参数

标签 c++ templates reference member-variables

首先,我有这样的东西:

class Test {
    std::vector<int> a, b;
    void caller(...) { callee(...); }
    void callee(...) { /* Do stuff with 'a' */ }
}

我想要的是拥有一个与 callee 完全相同的函数,但用于 vector b。为此,有两个明显的解决方案:

  • 传递 vector ab 作为参数。但是,callee 是一个递归函数,可以进行数百次调用,将 vector 作为参数传递只是不必要的开销。
  • 复制函数 callee 并使用 vector b,这将是最好的选择,尽管 callee 是一个相当长的函数而且我会有很多重复的代码。

出于好奇,我去寻找模板部分,我注意到它可以用于

lvalue reference type

pointer type

pointer to member type

所以我尝试这样做:

class Test {
    std::vector<int> a, b;
    void caller(...) { callee<a>(...); }
    template <std::vector<int> &x> void callee(...) { /* Do stuff with 'x' */ }
}

但是我明白了

error: use of ‘this’ in a constant expression

有什么方法可以通过引用或指针来实现吗?

顺便说一句,我想要的可以看作是函数范围的#define

最佳答案

数组甚至元组,但不喜欢古老的指向成员的指针?

class Test {
    std::vector<int> a, b;

    void caller(/*...*/) { callee<&Test::a>(/*...*/); }

    template <std::vector<int> Test::*vec>
    void callee(/*...*/) { /* Do stuff with `(this->*vec)` */ }
};

关于C++:将成员变量的引用/指针作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40401650/

相关文章:

c++ - Qt C++ 连接QPushButton 点击

c# - 位移和数据解释

c++ - boost::regex_search 拒绝接受我的论点

c++ - C++引用变量

ms-access - Solidworks 2016 SaveAs Access VBA 运行时错误 438

c++ - boost::pool 默认 block 数

c++ - 从函数类型中剥离所有限定符

c++ - 模板重载 ostream 运算符

c++ - doxygen C++ 内联模板文档

c++ - 这是一个有效的功能吗?