vendredi 27 mai 2016

Ignore a template spezialization and explicitly use the unspezialized template (std::vector

While working on some old code it encountered an std::unique_ptr<bool> used for storing some bool-values (allocated in class constructor and used as an array).

When I tried to replace it with a std::vector<bool> I encountered a problem when I had to call a library function which takes a pointer to bool (const bool*): There is a template specialization for std::vector<bool> which compresses 8 boolean values into one byte and therefore it is not possible to get a bool* pointer to the data without decompressing it first.

I have already found some solutions by Google search or the StackOverflow article C++11 vector<bool> performance issue (with code example) but none of them are working for me (i.e. using a struct which contains a boolean would work, but it makes the code I try to simplify more complex; std::valarray does not provide a data() member)

There is also an article "How to prevent specialization of std::vector<bool>" but all solutions there are just workarounds and I am not convinced of the phrase "bool and unsigned char typically take the same amount of memory on their own" (mentioned at pointing to an element of std::vector<bool>?)

I also checked Alternative to vector<bool> but we do not use boost in our solution and I am not willing to add this dependency for a single use.

My Question is: Is there a way to ignore a template spezialization and explicitly use the unspezialized template for a type?

For example

#include <iostream>

template<class T>
class MyTemplate
{
public:
  static const int Value = 0;
}

template<>
class MyTemplate<double>
{
public: 
  static const int Value = 1;
};

int main(int argc, char **argv)
{
  // How can I make MyTemplate<double> ignore the spezialization and output 0?
  std::cout << "0==" << MyTemplate<double>::Value << std::endl;

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire