Question

I'm using explicit template specialization to initialize a std::vector with information but only for a specific type of std::vector, thus the explicit specialization. Within the constructor, if I try to call push_back or any other existing function in std::vector, compilation fails. What is the problem and how do I fix it?

simplified example:

namespace std
{
  template<>
  class vector<int>
  {
  public:
    vector(void)
    {
      int value = 5;
      push_back(value);
    }
  };
}

compiler message:

In constructor 'std::vector<int>::vector()':
error: 'push_back' was not declared in this scope
       push_back(value);
                      ^
Was it helpful?

Solution

Explicit specializations are completely different classes that are separate from the primary template. You have to rewrite everything.

In normal situations where you control the primary template, you would typically have some sort of common base class or base class template to collect common structures.

With a given library, it is generally a very bad idea to add specializations (unless the library explicitly says it's OK). With the C++ standard library, this is outright undefined behaviour.

(The main problem is that other translation units may be using the template instantiation which you're specializing without seeing your specialization, which violates the one-definition rule.)

OTHER TIPS

Template specializations are unrelated types from both the primary template and any other specialization. It is unclear what you are attempting to do, as it is also illegal to provide specializations of templates in the std namespace unless the specialization uses your own user defined type.

If you can explain the problem to solve, you might get other options, like specializing a member function rather than the template itself...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top