gpt4 book ai didi

c++ - 将数组元素传递给模板

转载 作者:行者123 更新时间:2023-12-03 06:50:10 25 4
gpt4 key购买 nike

我认为下面的代码是不言自明的。我可以轻松地将静态变量传递给模板参数,并且它按预期工作。使用静态数组将清理代码,因此它看起来更好,但不幸的是,由于我在注释中粘贴的错误,它无法编译。请注意,它是由带有 c++17 标志的 gcc 10.2 编译的。
所以问题是如何将数组元素传递给模板。

#include <iostream>
#include <vector>
#include <tuple>

using DataTransfer = std::tuple<char, int>;
using DataPool = std::vector<DataTransfer>;

typedef struct Event
{
DataPool dataPool;
const char* description;
} Event;

template <Event& event>
class EventTransmitter
{
public:
EventTransmitter()
{
std::cout<<event.description<<"\n";
}
};

static Event ev1{ {{'d', 4}, {'a', 1}}, "Description 1"};
static Event ev2{ {{'g', 7}, {'b', 6}}, "Description 2"};

static Event evs[2] {
{ {{'d', 4}, {'a', 1}}, "Description 1"},
{ {{'g', 7}, {'b', 6}}, "Description 2"}
};

int main()
{
EventTransmitter<ev1> e1;
EventTransmitter<ev2> e2;

//EventTransmitter<evs[0]> e3;
//error: '& evs[0]' is not a valid template argument of
//type 'Event&' because 'evs[0]' is not a variable
return 0;
}

最佳答案

TL;DR 升级您的编译器,并希望它们完全实现 C++20。

问题纯粹是关于非类型模板参数的问题

template<int&>
struct S;

static int i;
static int arr[42];

S<i> s1;
S<arr[0]> s2; // ill-formed?
static也无关紧要,以防万一。
此规则存在于 C++17 [temp.arg.nontype]

For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer to (or for a pointer type, shall not be the address of):

  • a subobject, [...]

C++20中放松了

For a non-type template-parameter of reference or pointer type, [...] the reference or pointer value shall not refer to or be the address of (respectively):

  • a temporary object,
  • a string literal object,
  • the result of a typeid expression,
  • a predefined __func__ variable, or
  • a subobject of one of the above.

至于为什么,我只能假设标准谨慎地只需要非常小的值子集,以避免它无法实现的可能性。

关于c++ - 将数组元素传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64572884/

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