Reputation: 12953
I’m creating a new container. One of its template parameters is its initial capacity. As a result, creating instances with different initial capacities will result in the compiler generating the same code for each templated class.
MyVector<3> firstVector;
MyVector<4> secondVector;
...
if (firstVector.empty() && secondVector.empty())
{
...
}
This snippet would cause the compiler to generate empty()
for both classes. Can a compiler eliminate this redudancy?
Upvotes: 3
Views: 211
Reputation: 746
Does the empty() method use the template parameter? If not, you can factor it into a non-templated base class from which the templated class inherits.
Upvotes: 0
Reputation: 69988
Probably, compiler does not eliminate this. Consider following example:
template<size_t CAPACITY>
class MyVector {
...
public:
bool empty() const { static int i = CAPACITY; return ...; }
};
In above case, you can see that every MyVector<N>::empty()
has to be unique, because static int i
should be exclusive to the function. Even if the static int
is not present, compiler will always assume its possibility. So, if a copy of empty()
would be generated, it will be generated for all versions.
I am answering theoretically. Not aware if a compiler have some practical optimization technique, which would overcome such things.
However, if your MyVector
looks like this:
template<size_t CAPACITY, typename T>
class MyVector : public vector<T>
{
// using vector<T>::empty;
};
Then, only one copy would be generated.
Upvotes: 0
Reputation: 170479
First of all, empty()
will perhaps be very simple and the compiler will be able to inline it. What if is cannot be inlined? The compiler can do any kind of merging but it must do it in such way that distinct functions have distinct addresses:
&MyVector<3>::empty() != &MyVector<4>::empty()
Visual C++ 10 can exhibit non-standard behavior here depending on linker settings - with some settings it will detect such functions and just merge them thus violating the Standard. I haven't seen it ever doing such elimination in a Standard-compliant way.
Upvotes: 3