专门化模板从类到整数

时间:2015-09-03 13:08:42

标签: c++ templates c++11 template-specialization partial-specialization

我正在玩模板专业化以了解它们的限制,我现在尝试不基于类型进行专门化,而是使用整数参数。但我失败了。

例如,模板template <class T>应专门用于T,例如字符串,但有一个额外的模板参数template <int I>

标准说什么,我该怎么做(如果可以的话)?我的代码如下。

谢谢!

#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;
}

1 个答案:

答案 0 :(得分:1)

这是一种专门针对不同整数值的方法,它使用了一个额外的类型,你必须进一步专门化。 这非常简单:

#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;
}