簡體   English   中英

將數組元素傳遞給模板

[英]Passing array element to template

我認為下面的代碼是不言自明的。 我可以輕松地將靜態變量傳遞給模板參數,並且它按預期工作。 使用靜態數組將清理代碼,因此它看起來更好,但不幸的是,由於我在注釋中粘貼的錯誤,它無法編譯。 請注意,它是由帶有 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]

對於引用或指針類型的非類型模板參數,常量表達式的值不得引用(或對於指針類型,不得為以下地址):

  • 一個子對象,[...]

C++20 中放松了

對於引用或指針類型的非類型模板參數,[...] 引用或指針值不應引用或作為(分別)的地址:

  • 一個臨時對象,
  • 一個字符串文字對象,
  • typeid 表達式的結果,
  • 預定義的 __func__ 變量,或
  • 以上之一的子對象。

至於為什么,我只能假設標准謹慎地只需要非常小的值子集,以避免它無法實現的可能性。

這里有一個答案(已刪除)讓我知道如何解決它。 它並不完美,但也不錯。

#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;
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM