我有一个带有模板参数的类,我想调用它的一个方法。它看起来是这样的:如何根据模板参数创建一个const方法?
template <typename T>
class Foo {
public:
void doSomething() {
for (auto& t: ts) {
t.doSomething();
}
}
private:
std::vector<T> ts;
};
这工作,但我想使doSomething()
常量如果T
本身是常量(假设T::doSomething()
将是const太)。我找到了一个可能的解决方案(基于this question),但我不喜欢它。
template <bool enabled = std::is_const<T>::value>
typename std::enable_if<enabled, void>::type
doSomething() const {
for (auto& t: ts) {
t.doSomething();
}
}
template <bool enabled = !std::is_const<T>::value>
typename std::enable_if<enabled, void>::type
doSomething() {
for (auto& t: ts) {
t.doSomething();
}
}
它工作正常,但它有一个代码重复。有什么办法可以避免它?
作为workarround您可以添加'私营:属性(always_inline)_doSomething',并呼吁从你的'(常量)dosomething' – ted