gpt4 book ai didi

c++ - 重新映射模板参数结构

转载 作者:太空狗 更新时间:2023-10-29 23:13:01 24 4
gpt4 key购买 nike

我是模板的新手,想知道如何执行以下操作:我有一个允许定点计算的定点结构,定义如下:

template<int bits, int offset>
struct Fixed {
int64_t raw;
inline Fixed() {}
...
}

我想扩展它,以便我可以声明一个自定义的浮点表示,编译器将其转换为正确的定点定义。我试过如下:

template<int totBits, int expBits, int expOffset>
struct Fixed<exp2(expBits)+totBits-expBits-2,expOffset-totBits+expBits> {
inline Fixed() {}
inline explicit Fixed(double value) {
Quantization function of floating point here
}
};

但是,这给了我错误:“模板参数涉及模板参数”。

如何重新映射初始模板,以便执行以下操作:fixed::Fixed<8,3,0> foo;编译器将其视为:fixed::Fixed<11,-3> foo;

我知道当我给 foo 赋值时我将不得不手动量化它,就像它存储为 float 一样:例如foo = fixed::Fixed<8,3,0>(243)这将给出 foo = 240 和 foo = fixed::Fixed<8,3,0>(244)将给出 foo = 248。

最佳答案

一种方法是制作Fixed<bits, offset> Fixed<totBits, expBits, expOffset> 的特化, 使用无效值作为 expOffset .

// Forward definition.  Third parameter defaults to an invalid value for expOffset.
// Replace default if necessary.
template<int, int, int = 256>
struct Fixed;

// "Main" specialisation. Used when third parameter is an invalid expOffset.
// Specialises for when third parameter is default.
template<int bits, int offset>
struct Fixed<bits, offset, 256> {
int64_t raw;
inline Fixed() {}

// Dummy implementation for example.
inline Fixed(int64_t value) : raw(24) {
std::cout << "Fixed<" << bits << ", " << offset << ">(" << value << ")\n";
}
};

// Non-specialised implementation, used for any other value of expOffset.
// Inherits from main specialisation.
template<int totBits, int expBits, int expOffset>
struct Fixed : Fixed<static_cast<int>(exp2(expBits))+totBits-expBits-2,expOffset-totBits+expBits> {
using MyBase = Fixed<static_cast<int>(exp2(expBits))+totBits-expBits-2,expOffset-totBits+expBits>;

// Dummy implementation for example.
inline explicit Fixed(double value) : MyBase(42) {
std::cout << "Fixed<" << totBits << ", " << expBits << ", " << expOffset << ">(" << value << ")\n";
}
};

这允许第二个变体的实例化继承自第一个变体的适当实例化,同时使用相同的名称。

int main() {
std::cout << "f1:\n";
Fixed<11, -3> f1(1);
std::cout << "\nf2:\n";
Fixed<8,3,0> f2(1.0);
}

Output :

f1:
Fixed<11, -3>(1)

f2:
Fixed<11, -5>(42)
Fixed<8, 3, 0>(1)

请注意,这实际上是正常的继承,尽管基类和派生类都是同一模板的特化;因此,将第二个版本作为一个单独的类可能会更清楚地传达您的意图。

关于c++ - 重新映射模板参数结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42461196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com