如何使用整数类型本身为整数类型专门化 class 模板?

How to specialize a class template for an integral type with the integral type itself?

我有一个 class 模板 X 如下所示:

template <typename T>
class X {
 public:
   X(T &t): t_ {t} {}

 private:
   T &t_;
};

有没有办法针对 T = int 专门化它,使得整数 i 的表达式 X<int>(i) 除了 "returns" 什么都不做,只是 i 编译时间?

换句话说,我希望 doubleint(分别为 X<double>(d)X<int>(i))具有相同的语法,但前者调用一个构造函数如上面的代码所示初始化一个引用,而后者忽略 "syntax sugar" 和 "returns" 整数 i 而不做任何事情。

您可以分别为 intdouble 提供模板特化并使用转换运算符。像这样:

// the same applies for double
template<>
class X<int> {
 public:
   constexpr X(int t) : t_ {t} {}

   constexpr operator int() const { return t; }

 private:
   int t_;
};

这将使类似下面的东西起作用(如果我误解了你的问题请纠正我):

constexpr int n = X<int>(20); // n == 20