gpt4 book ai didi

模板中的 C++ 运行时变量

转载 作者:行者123 更新时间:2023-11-30 03:49:43 25 4
gpt4 key购买 nike

template <int ns, int id>
class Bar
{
public:
static int value;
};

template <int ns, int id>
int Bar<ns, id>::value = 0;

class Foo
{
public:

template <int ns, int id>
static int GetNextValue()
{
++Bar<ns, id>::value;
return Bar<ns, id>::value;
}

};

class Baz
{
public:
Baz(int value)
: value(value)
{
}

void PrintBaz();
private:
int value;
};

这样调用时效果很好:

Baz baz(Foo::GetNextValue<1, 1>());

我需要此代码来支持以下内容。

int ns = 1;
int id = 5;
Baz baz(Foo::GetNextValue<ns, id>());

此代码的编译失败是可以理解的。有没有办法让模板元编程支持运行时变量值?

通过任何其他方法解决此问题的指针也会有所帮助。

最佳答案

简单的答案是否定的,模板是一个编译时构造。如果您需要可以在编译时或运行时计算的代码,您可能需要考虑 constexpr 函数。

关于模板中的 C++ 运行时变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280433/

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