类包装器的模板特化

时间:2021-04-19 07:40:32

标签: 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&,但我希望有其他更好的方法来解决这个问题。

1 个答案:

答案 0 :(得分:3)

您可以轻松地使 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

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

相关问题