且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++模板:根据模板参数的值选择不同的类型

更新时间:2023-11-11 16:29:16

通过专业化:

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;