将数组元素传递给模板

doc*_*ocp 6 c++ arrays templates c++17

我认为下面的代码是不言自明的。我可以轻松地将静态变量传递给模板参数,并且它按预期工作。使用静态数组将清理代码,因此它看起来更好,但不幸的是,由于我在注释中粘贴的错误,它无法编译。请注意,它是由带有 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;
}  
Run Code Online (Sandbox Code Playgroud)

doc*_*ocp 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, int index>
class EventTransmitter
{
    public:
    EventTransmitter()
    {
        std::cout<<(event+index)->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;
    EventTransmitter<evs, 1> e4;

    return 0;
}  
Run Code Online (Sandbox Code Playgroud)