I have a class with a template parameter, and I want to call a method of it. It looks something like this:
template <typename T>
class Foo {
public:
void doSomething() {
for (auto& t: ts) {
t.doSomething();
}
}
private:
std::vector<T> ts;
};
This works, but I want to make doSomething()
const if T
itself is const (it is assumed that T::doSomething()
will be const too). I found a possible solution (based on this question), but I don't like it.
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();
}
}
It works fine, but it has a code duplication. Is there any way to avoid it?