简体   繁体   English

如何使用以“constexpr”声明的结构作为模板参数?

[英]How to use a struct declared with 'constexpr' as a template parameter?

Image you have a struct as follows:图像你有一个结构如下:

typedef struct {
    int a;
    int b[2];
    int c;
} DataParameters;

In a specific situation, you know all these values at compile time:在特定情况下,您在编译时就知道所有这些值:

constexpr DataParameters p = {
    .a = 5,
    .b = {3, 3},
    .c = 12
};

You then want to create a template function which uses the values of a, b, c.然后,您要创建一个模板 function,它使用 a、b、c 的值。 The following syntax is valid since the struct is declared as constexpr .以下语法是有效的,因为结构被声明为constexpr

template<int A, int B_0, int B_1, int C>
void doSomething() {
    ...
}

doSomething<p.a, p.b[0], p.b[1], p.c>();

But let's say you have a struct that is much bigger and you do not want a giant list of template parameters.但是,假设您有一个更大的结构,并且您不想要一个巨大的模板参数列表。 Is there any better way to it?有没有更好的方法呢? I've tried the following, but get compiler errors:我尝试了以下方法,但得到编译器错误:

template<const DataParameters& P>
void doSomething() {
    ...
}

doSomething<p>();

Any suggestions?有什么建议么?

Since C++11 you can have template <const DataParameters& P> with objects that have static storage duration and either external or internal linkage.由于 C++11 您可以使用template <const DataParameters& P>与具有 static 存储持续时间和外部或内部链接的对象。

Since C++17 you can have template <const DataParameters& P> with objects that have static storage duration (the linkage restriction was removed)由于 C++17 您可以使用template <const DataParameters& P>与具有 static 存储持续时间的对象(链接限制已删除)

Since C++20 you can have template <DataParameters P> .从 C++20 开始,您可以拥有template <DataParameters P> The non-type parameter can be (since C++20):非类型参数可以是(C++20 起):

  • a literal class type with the following properties:具有以下属性的文字 class 类型:
    • all base classes and non-static data members are public and non-mutable and所有基类和非静态数据成员都是公共的和不可变的,并且
    • the types of all bases classes and non-static data members are structural types or (possibly multi-dimensional) array thereof.所有基类和非静态数据成员的类型都是结构类型或其(可能是多维的)数组。

https://en.cppreference.com/w/cpp/language/template_parameters https://en.cppreference.com/w/cpp/language/template_parameters

struct DataParameters // don't use C style typedef
{
    int a;
    int b[2];
    int c;
};

template <const DataParameters& x>
void foo() {}

constexpr DataParameters gp{};

void test_ref_global()
{
    foo<gp>(); // ok since C++11
}

void test_ref_local()
{
    static constexpr DataParameters p{};    
    foo<p>(); // ok since C++17
}

template <DataParameters x> // ok since C++20
void bar() {}

auto test_val()
{
    constexpr DataParameters p{};
    bar<p>(); // ok since C++20
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM