[英]How to have array size depending on parameter in class using template
I have a graph consisting of Q-tuples, where Q is either 3 or 6. The nodes in the graph are modeled as typedef std::array<int,3> NODE
or typedef std::array<int,6> NODE
respectively.我有一个由 Q 元组组成的图,其中 Q 为 3 或 6。图中的节点分别建模为
typedef std::array<int,3> NODE
或typedef std::array<int,6> NODE
. To be more flexible I used a template class为了更灵活,我使用了模板 class
template <int Q>
class DARP
{
// some attributes
int capacity = Q;
typedef std::array<int,Q> NODE;
NODE depot;
void create_nodes();
};
However, the following implementation results in an error.但是,以下实现会导致错误。
template <int Q>
void DARP<Q>::create_nodes()
{
if (capacity == 3)
depot = {0,0,0};
else
depot = {0,0,0,0,0,0};
}
This can be fixed by这可以通过
template <int Q>
void DARP<Q>::create_nodes()
{
for (int i=0; i<Q; i++)
{
depot[i] = 0;
}
}
but when I'd like to create more complicated nodes like {0,1,4,8,9,10}
it would come in handy to be able to write it in this "short" form.但是当我想创建像
{0,1,4,8,9,10}
这样更复杂的节点时,能够以这种“短”形式编写它会派上用场。 Is there any way to handle this more elegantly?有没有办法更优雅地处理这个问题?
You can use Constexpr If (since C++17) with template parameter Q
as:您可以将Constexpr If (C++17 起) 与模板参数
Q
一起使用:
if constexpr (Q==3)
depot = {0,0,0};
else
depot = {0,0,0,0,0,0};
According to the condition value, the statement-true or statement-false will be discarded and then won't cause the error.根据条件值, statement-true或statement-false将被丢弃,不会导致错误。
Before C++17, you can specify create_nodes
as:在 C++17 之前,您可以将
create_nodes
指定为:
template <>
void DARP<3>::create_nodes()
{
depot = {0,0,0};
}
template <>
void DARP<6>::create_nodes()
{
depot = {0,0,0,0,0,0};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.