C++模板模板语法:简单性与可用性为什么不是“自动”

swvgeqrz  于 2022-11-27  发布在  其他
关注(0)|答案(2)|浏览(101)

下面的第一段代码在一行中用“class”这个词五次发汗后编译得很好,并在shelf〈std::vector,int〉top_shelf的“main”中定义;在我看来太支离破碎了,所有这些都只是摘录了“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”?另一件事为什么不'auto'在这里:

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

这很有道理:auto =〉'box'模板结构。
那么有没有办法从第二个代码中去掉“E类”呢?

xdnvmnnf

xdnvmnnf1#

如果T是向量类型,那么可以通过T::value_type得到值类型:

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

    // ⋮
};
zdwk9cvp

zdwk9cvp2#

不允许将auto作为模板参数传递。
您可以使用shelf<decltype(box)>代替shelf<auto>,如下所示:

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

相关问题