簡體   English   中英

c++ template 模板語法:簡單性 vs 可用性為什么不用“auto”

[英]c++ template template syntax: simplicity vs useability why not 'auto'

下面的第一段代碼在一行中用了五次“class”這個詞后編譯得很好,並且定義在 shelf<std::vector, int> top_shelf 的“main”中; 對我來說看起來太零散了,所有這些只是從容器中提取“class E: value_type”。我需要這個 type_value 所以我可以保留 dummy:garbage_value 以防錯誤超出通過容器索引的范圍,例如:

  E& return_value_type_at(int x ){ return check(x)? (*container)[x] : garbage_value; }

這是第一個代碼:

#include <iostream>
#include <vector>

template< template<class, class> class C, class E, class A = std::allocator<E> >
class shelf
{
  C<E,A>* container;
// E garbage_value; // not completely implemented
  public:
// bool check(x);
  shelf(C<E,A>& x) : container{&x}{ }
  E& return_value_type_at(int x ){ return /*check(x)?*/(*container)[x]/* : garbage_value*/; }
};

int main()
{
  std::vector<int> box = {1,2,3,4};
  shelf<std::vector,int> top_shelf{box};
  return 0;
}

下面的第二個代碼,編譯得很好,看起來簡單多了:

#include <iostream>
#include <vector>

template<class T>
class shelf
{
  T* container;
  public:
  shelf(T& x) : container{&x}{ }
  auto& value_type_at(int x ){ return (*container)[x]; }
};

int main()
{
  std::vector<int> box = {1,2,3,4};
  shelf< std::vector<int> > top_shelf{box};
  return 0;
}

這里關鍵字“auto”幫助了我,因為我不知道用什么替換它,這同樣是一個問題,我將如何處理“garbage_value”? 另一件事為什么不在這里“自動”:

/home/insights/insights.cpp:16:9: error: 'auto' not allowed in template argument
  shelf<auto> top_shelf{box};
        ^~~~

這很有意義:auto => 'box' 模板結構。

那么有沒有辦法從第二個代碼中獲取“E類”?

auto不允許作為模板參數傳遞。

您可以使用shelf<decltype(box)>而不是使用shelf<auto> ,如下所示:

shelf<decltype(box)> top_shelf{box}; //works now

如果T是向量類型,則可以通過T::value_type獲取值類型:

template<typename T>
class shelf
{
    T::value_type garbage_value;

    // ⋮
};

暫無
暫無

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

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