首先,我有这样的东西:
class Test {
std::vector<int> a, b;
void caller(...) { callee(...); }
void callee(...) { /* Do stuff with 'a' */ }
}
我想要的是拥有一个与 callee
完全相同的函数,但用于 vector b
。为此,有两个明显的解决方案:
- 传递 vector
a
或b
作为参数。但是,callee
是一个递归函数,可以进行数百次调用,将 vector 作为参数传递只是不必要的开销。 - 复制函数
callee
并使用 vectorb
,这将是最好的选择,尽管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/