gpt4 book ai didi

c++ - 模板参数中的函数调用

转载 作者:太空狗 更新时间:2023-10-29 20:02:42 24 4
gpt4 key购买 nike

我正在为以下情况而苦苦挣扎。

#include "systemc.h"

template<int maxval>
class Foo {
/* Error: calls to constructors and functions cannot be part of a constant expression */
sc_uint<int(log2(double(maxval)))> a;
...
};

int main() {

Foo<10> foo;
...
return 0;
}

正如您在上面看到的,模板类“Foo”具有模板参数“maxval”。 'Foo' 还拥有一个成员,同样是一个模板化类,它在其模板参数中使用模板参数 'maxval' 和函数 'log2' 进行实例化。但是,所描述的代码将不起作用,因为例如函数调用不能是常量表达式的一部分。你看到任何评估的可能性吗? log2(maxval) 在编译期间并将结果用于 'Foo' 内的更多模板参数?

感谢您的帮助。(我使用的是 GCC 4.1.2)

最佳答案

模板期望编译时值。 log2函数需要是 constexpr为了这个工作(它不是)。

您必须定义自己的 constexpr功能。在以 2 为底的对数函数的情况下,如果您需要一个整数(切断浮点部分),它可以工作:

constexpr int log2(int number, int acc = 0) {
return number <= 1 ? acc : log2(number / 2, acc + 1);
}

编辑:

我没有注意到问题是针对不支持 constexpr 的 GCC 4.1 提出的.虽然您应该尝试升级(如果您可以使用该选项),但您也可以按照@Florian 的回答中的建议使用基于模板的解决方案。

编辑 2:

如果您不想依赖 Boost,可以使用以下基于模板的简单实现:

template<int V>
struct log2 {
static int const value = 1 + log2<V/2>::value;
};

template<>
struct log2<0> {};

template<>
struct log2<1> {
static int const value = 0;
};

然后您可以将其用作 log2<13>::value ,这将导致 3 .

另一个编辑:

constexpr上面的实现将返回 0对于 0和负数,这是一个错误。对数未定义为零值或负值(在实数域中),因此可以调整该函数以引发错误(因为它有点不可读,我添加了一些换行符以进行格式化):

constexpr int log2(int number, int acc = 0) {
return number <= 0
? throw std::logic_error{"Logarithm of zero or negative number not allowed."}
: number == 1
? acc
: log2(number / 2, acc + 1);
}

关于c++ - 模板参数中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36977111/

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