C ++模板:根据模板参数的值选择不同的类型 [英] C++ templates: Select different type based on value of template parameter

查看:40
本文介绍了C ++模板:根据模板参数的值选择不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在C ++中完成以下工作,以及所谓的这种事情是什么?

How do I accomplish the following in C++, and what is doing such things called?

template <bool S>
class NuclearPowerplantControllerFactoryProviderFactory {
  // if S == true
  typedef int data_t;
  // if S == false
  typedef unsigned int data_t;
};

推荐答案

通过专业化:

template <bool> class Foo;

template <> class Foo<true>
{
  typedef int data_t;
};

template <> class Foo<false>
{
  typedef unsigned int data_t;
};

您可以选择将两种情况之一设为主要模板,将另一种情况设为专业化,但是考虑到 bool 只能具有两个值,因此我更喜欢这种对称的版本.

You can choose to make one of the two cases the primary template and the other one the specialization, but I prefer this more symmetric version, given that bool can only have two values.

如果这是您第一次看到此内容,您可能还想考虑 partial 专业化:

template <typename T> struct remove_pointer     { typedef T type; };
template <typename U> struct remove_pointer<U*> { typedef U type; };

如@Nawaz所说,最简单的方法可能是 #include< type_traits> 并说:

As @Nawaz says, the easiest way is probably to #include <type_traits> and say:

typedef typename std::conditional<S, int, unsigned int>::type data_t;

这篇关于C ++模板:根据模板参数的值选择不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆