有条件的专业化

Conditional Specialization

假设我有以下内容:

template<std::size_t> struct s;
template<> struct s<sizeof(int)>  { /*...*/ };
template<> struct s<sizeof(long)> { /*...*/ }; // will not compile as it already exists.

如何执行检查以有条件地区分两个实例化?当且仅当它们不相等时,我才想实现后者。

显然,sizeof 不是可以由预处理器计算的结构。我有哪些选择?

您可以让两个专业化都采用(不受约束的)std::size_t,并且仅在 == sizeof(int)== sizeof(long) && sizeof(long) != sizeof(int) 时启用专业化:

#include <type_traits>
#include <cstddef>

template<std::size_t, typename = void> struct s;

template<std::size_t N>
struct s<N, std::enable_if_t<N == sizeof(int)>> { /* ... */ };

template<std::size_t N>
struct s<N, std::enable_if_t<N != sizeof(int) && N == sizeof(long)>> { /* ... */ };

如果你能保留一个“无效”值,你可以替换它以避免冲突:

template<std::size_t> struct s;
template<> struct s<sizeof(int)> { /*...*/ };
template<> struct s<sizeof(long)==sizeof(int) ? -1 : sizeof(long)> { /*...*/ };

有时也可以使用 if constexpr 而不是显式特化,这样重复就不会出错。