0

I am playing with template specializations to learn their limits, and I was trying now not to specialize based on type, but using an integer parameter. But I am failing.

For instance, a template template <class T> should be specialized to have T for instance a string, but having an additional template parameter as template <int I>.

What does the standard say, and how can I do (if it can be done)? My code follows.

Thanks!

#include <iostream>
#include <typeinfo>
#include <tuple>
#include <string>

template <class T, class... U>
class many
{
public:

  T t;

  std::tuple<U...> u;
};


template <int size>
class many<int>
{
    // ???
};

int main(int argc, char* argv[])
{
  many<int, std::string, char> m;

  m.t = -1;

  std::get<0>(m.u) = "hello";
  std::get<1>(m.u) = 'w';

  std::cout << "many: " << std::endl;
  std::cout << m.t << std::endl;
  std::cout << std::get<0>(m.u) << std::endl;
  std::cout << std::get<1>(m.u) << std::endl;


  return 0;
}
senseiwa
  • 2,369
  • 3
  • 24
  • 47

1 Answers1

1

Here's a way to specialize it for different integer values, it uses an extra type that you have to specialize further. It is pretty straightforward:

#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <type_traits>

#include <string>

template <class T, class... U>
struct many
{
  T t;
  std::tuple<U...> u;
};

template<int N>
using Int = std::integral_constant<int, N>;

typedef Int <1> One;
typedef Int <2> Two;

template <>
struct many<int>
{ };

template <>
class many<One>
{ };

template <>
class many<Two>
{ };

int main(int argc, char* argv[])
{
  many<int, std::string, char> m;
  many<One, char> m2;
  m.t = -1;
  std::get<0>(m.u) = "hello";
  std::get<1>(m.u) = 'w';

  std::cout << "many: " << std::endl;
  std::cout << m.t << std::endl;
  std::cout << std::get<0>(m.u) << std::endl;
  std::cout << std::get<1>(m.u) << std::endl;
}
dau_sama
  • 4,247
  • 2
  • 23
  • 30
  • This is the best approach I can think of, too. Though it's better to use what the STL provides: http://en.cppreference.com/w/cpp/types/integral_constant – Daniel Jour Sep 03 '15 at 16:07
  • nice, I didn't know about `integral_constant`, it would be indeed allow to reuse the stl to do basically what I've coded. Traits are paramount in the stl, it sort of makes sense that there was something there already. Thanks! – dau_sama Sep 03 '15 at 16:10
  • 1
    @DanielJour I upgraded the answer to use `integral_constant` – dau_sama Sep 04 '15 at 07:46