我不能让我的 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;
}
并且这些值将是等价的,即使它们来自具有不同身份的对象。
关于c++ - 类包装器的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67157822/