My particular case involves a custom iterator, but this question is a general one. I'm unsure how to write the return type for this postfix increment method:
template<typename T>
struct MyIterator {
size_t loc;
MyIterator operator++(int) {
MyIterator temp(*this);
++loc;
return temp;
}
};
This compiles, but so does this:
template<typename T>
struct MyIterator {
size_t loc;
MyIterator<T> operator++(int) {
MyIterator<T> temp(*this);
++loc;
return temp;
}
};
The two other configurations also work fine (i.e. putting the <T>
on only one of the instances of MyIterator
). Is there a "correct" way to write this? Does it matter?
答案 0 :(得分:8)
Is there a "correct" way to write this?
Both names are correct. However, using the injected class name is simpler and preferable, especially if there are more than one template parameters. Imagine you have:
template <typename T1, typename T2, typename T3> class MyClass { ... };
Inside the class template, it is preferable to use MyClass
than MyClass<T1, T2, T3>
.
Does it matter?
No.
Since you are inside the scope of the class, the name lookup will find what you expect. This has to do with injected class name, and I suggest you to read more about it here: Why is there an injected class name?
Since c++14, another correct way to do it is auto
with no trailing return type, as skypjack mentioned.