【问题标题】:Template for constructor构造函数模板
【发布时间】:2019-10-08 17:46:39
【问题描述】:

我看到一个类的构造函数很奇怪:

class HashTable
{
public:
    template <int N>
    HashTable(const char(&str)[N])

    {
    }
};

能否请您解释一下并提供一些示例或给我一个相关链接? 我真的不明白const char(&amp;str)[N]。

【问题讨论】:

  • 哪一部分你不明白?你知道模板吗?你知道const char(&amp;str)[N] 是什么吗?请尝试更具体
  • 老实说,每次遇到一段你不理解的代码作为你的第一个 goto 解决方案时,写一个问题并不是一个好策略。也许看看这里stackoverflow.com/questions/388242/…
  • 没有找到好的副本,但这是非常相关的:stackoverflow.com/questions/2188991/… 如果您浏览答案,您还会找到一个解释模板技巧以获取数组大小的答案
  • 你想知道的关于 const char(&str)[N] 的内容。看不懂这个小代码

标签: c++ c++11


【解决方案1】:

这是一种捕获数组参数大小的方法。数组的类型为T[N],通常可以衰减为T*。

#include <iostream>

template <int N>
void foo(const char(&str)[N]){
    for(int i=0;i<N;++i)
        std::cout<<str<<' ';
}

void foo(const char* str){
    //for(int i=0;i<??;++i)
}

void bar(const char* str, int n){
    for(int i=0;i<n;++i)
        std::cout<<str<<' ';
}
int main(){
    const char str[] =  "Hello";//type is const char[6]
    const char* str2 = str; //Decay
    // const char str3[] = str; (6)
    int n = sizeof(str)/sizeof(str[0]);
    foo(str);// (1) Calls foo<6>
    foo(str2);// (2) Must call foo(const char*) which is useless
    bar(str, n); // (3) Array can decay
    bar(str2, n); // (4) Same as (3) - bar can be used with all arrays
    bar(str2, 10); // (5) Buffer overrun
}

上面的例子展示了模板化方法的使用和限制。优点是您不必单独传递大小,因此它始终是正确的。最大的缺点是衰减过程是不可逆的,因此函数变得无用 - (2) 无法调用模板。

该模板很方便,但大多数数组通过bar 传递它们相当快地衰减为指针 - 这是C 中的唯一方法 - 或者仅仅是因为它们的大小在编译时未知 - malloc, new。另一个问题是在 C 和 C++ (6) 中都是无效的——没有隐式的方法来复制数组。因此bar 方法更为常见,但需要格外小心才能传递正确的大小。正确的 c++ 方法是使用std::vector 或std::array,除非它们被证明是瓶颈。

【讨论】:

  • 也许值得注意的是,在 char* 的情况下,正确的 c++ 方式是使用 std::string。
猜你喜欢
  • 2011-05-24
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多