简体   繁体   English

如何使用模板根据 class 中的参数设置数组大小

[英]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> NODEtypedef 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-truestatement-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.

相关问题 类模板中std :: array的大小取决于模板参数 - Size of std::array in class template depending on template parameter 根据类模板参数使std:array大小 - Make std:array size depending on class template parameter 由于非类型模板参数而导致数组大小为零的类模板:如何预防警告? - Class-template with zero-size array due to non-type template parameter: how to prevent warning? 如何从枚举类值中指定模板函数参数中的数组大小? - How to specify an array size in a template function parameter from an enum class value? 具有隐式数组大小的模板参数 - Template Parameter with implicit array size 捕获数组模板参数的大小 - Capture size of array template parameter C++ class 模板与非类型参数取决于使用 C++11 的类型参数问题 - C++ class template with non-type parameter depending on type parameter problem using C++11 使用SFINAE更改类中调用的函数,具体取决于类模板参数的类型 - using SFINAE to change function called in a class depending on type of class template parameter 如何将嵌套模板类实例化设置为默认模板参数,具体取决于其他参数 - How to set, as default template parameter, a nested template class instanciation depending on other parameters 当定义为模板参数时,编译器如何推断数组大小? - How does the compiler deduce array size when defined as a template parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM