c++ - 类包装器的模板特化

标签 c++ c++17 c++20

我不能让我的 int 类包装器像模板特化中的原始 int 一样。

我准备了这段代码来详细解释我的问题:

#include <iostream>
#include <stdlib.h> 

class Integer
{
  int _v;
public:
  constexpr explicit Integer(int v) : _v(v) {}
  constexpr Integer next() const { return Integer(_v + 1); }
  constexpr operator int() const { return _v;}
};

static constexpr auto integer1 = Integer(1);
static constexpr auto integer2a = Integer(2);
static constexpr auto integer2b = integer1.next();

template <const Integer& i>
void foo_Integer()
{
  static auto foo_id = rand();
  std::cout << foo_id << std::endl;
}

static constexpr auto int1 = 1;
static constexpr auto int2a = 2;
static constexpr auto int2b = int1 + 1;

template <int i>
void foo_int()
{
  static auto foo_id = rand();
  std::cout << foo_id << std::endl;
}

int main()
{
  foo_int<int1>();
  foo_int<int2a>();
  foo_int<int2b>(); // same template specialization as above -> :)

  foo_Integer<integer1>();
  foo_Integer<integer2a>();
  foo_Integer<integer2b>(); // different template specialization -> :(
}

如你所见运行代码

foo_int<int2a>();
foo_int<int2b>();

使用相同的模板特化,同时

foo_Integer<integer2a>();
foo_Integer<integer2b>();

使用不同的模板特化。

从编译器的角度来看,这当然是正确的,因为模板接受 const Integer&,但我希望有其他更好的方法来解决这个问题。

最佳答案

您可以轻松地使 Integer 成为结构类型 (C++20)。然后它的值是有效的模板参数。

class Integer
{
public:
  int _v;

  constexpr explicit Integer(int v) : _v(v) {}
  constexpr Integer next() const { return Integer(_v + 1); }
  constexpr operator int() const { return _v;}
};

template <Integer i>
void foo_Integer()
{
  static auto foo_id = rand();
  std::cout << foo_id << std::endl;
}

Live

并且这些值将是等价的,即使它们来自具有不同身份的对象。

关于c++ - 类包装器的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67157822/

相关文章:

c++ - boost::flat_set 的迭代器无法合并

c++ - 将其返回值保存在 lambda 函数中时,std::ranges::sort 不能用作 'constexpr' 函数

c++ - 创建嵌套类的实例

c++ - 如果加法表达式的第一个操作数可转换为指针和整数,选择哪种转换?

c++ - 强制 gsl::as_span 返回一个 gsl::span<const T>?

c++ - 在 C++ 中比较结构时未找到 == 运算符

c++ - 如何将代码点转换为 utf-8?

c++ - 编译时检查是否有两个具有相同模板参数的模板实例化

c++ - 类似于 `declval` 的概念

c++ - 特定于类的释放函数可以在常量表达式中使用吗?