[英]Specialize template from class to integer
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>
. 例如,模板template <class T>
应该专门用于具有T
(例如字符串),但具有一个额外的模板参数作为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;
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.