gpt4 book ai didi

c++ - 参数列表中的可选 "name"?

转载 作者:行者123 更新时间:2023-11-28 01:37:19 24 4
gpt4 key购买 nike

template < parameter-list > declaration

参数列表中的每个参数可能是:

  • 一个非类型模板参数;
  • 类型模板参数;
  • 模板模板参数。

几分钟前,我找到了

  • template<typename>/*(a type template parameter)*/
  • template<int>/*a non-type template parameter*/

在某些情况下是合法的。

所以,语法是这样的:

  • 一个类型模板参数;
    • typename 名称(可选)
  • 一个非类型模板参数;
    • 输入姓名(可选)
  • ...

举个例子

template <typename T>
class ArrayList
{
std::vector<T> vec;
public:
template<class> // Mark!
class Ref {
ArrayList<T> *array;
int position;
public:
Ref(ArrayList<T> *a, int pos):array(a), position(pos) {};
Ref<T> &operator=(T v) {
if (array->vec.size() <= position)
array->vec.resize(position+1);
array->vec[position] = v;
}
operator T() const {
if (array->vec.size() <= position)
throw std::exception();
return array->vec[position];
}
};
Ref<T> operator[](int p) {return Ref<T>(this, p); };
};

我在函数的参数中知道类似的习语 type fun(type) {} , 它的唯一用途是我们不需要 name , type这里就够了。

我的问题是:

  1. 在执行Ref , 有什么好处template<class>而不是 template<class T>template<class U> .我想这是因为我们不需要额外的 T/U这里(准确的说是U,因为额外的T会导致shadowing error)template <typename T> class ArrayList
  2. 成语的其他好处是什么?(当然,也许没有其他好处)
  3. 除了注入(inject)类,什么时候排除多余的nameparameter-list .我希望看到更多的应用程序。

最佳答案

  1. 在您的特定示例中,没有任何好处。它无缘无故地使 Ref 成为成员模板。

  2. 如果我们将模板视为元函数,其好处(如果您可以这样调用它)与函数参数相同。我们可以表示该参数被忽略,并且不会影响最终的特化。您可以在标签分发代码中看到它。例如:

    template<typename> struct tag{};

    template<typename T>
    void do_foo_for(tag<T>) = delete;

    void do_foo_for(tag<int>) {
    // Do stuff
    }

    void do_foo_for(tag<std::string>) {
    // Do stuff
    }

    template<typename T>
    void foo() {
    do_foo_for(tag<T>{});
    }

    在上面,我们使用 tag 模板来创建一个廉价的类型来执行重载解析。当我们希望模板函数的实现根据类型参数而有所不同时,通常会这样做。由于重载通常比函数模板特化更健壮,我们根据从 tag 模板生成的不同类型进行重载。类型对于各种重载很重要,但对于模板本身,类型的名称根本不重要,所以我们不费心去命名它。

    标签分派(dispatch)的用途过于广泛,无法在此处进行描述,因此以上只是一个玩具示例。但它演示了如何根据“类型”分派(dispatch)函数。

关于c++ - 参数列表中的可选 "name"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48730640/

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