Template for constructor

led*_*ien -3 c++ c++11

I see one constructor of class so strange:

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

    {
    }
};
Run Code Online (Sandbox Code Playgroud)

Could you please explain it and some example or give me a related link? I really don't understand const char(&str)[N].

Qui*_*mby 5

这是一种捕获数组参数大小的方法。数组的类型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
}
Run Code Online (Sandbox Code Playgroud)

上面的示例显示了模板化方法的用法和局限性。优点是您不必分别传递大小,因此它总是正确的。最大的缺点是衰减过程是不可逆的,因此该函数变得无用-(2)无法调用模板。

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

  • 也许值得注意的是,对于char *,正确的c ++方法是使用std :: string。 (2认同)