模板化 c 字符串包装器中的大小扣除

Pin*_*tle 1 c++ arrays template-argument-deduction

为什么这不起作用:

#include <cstring>

template<size_t sz>
struct wstr {
    wchar_t _str[sz];

    wstr(const wchar_t source[sz]) {
        wcscpy_s(_str, source);
    }
};


int main(int argc, char** argv) {

    wstr ws = L"Hello"; //needs template argument

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

L"Hello"众所周知,它是一个const wchar_t[6].

sup*_*per 6

要使模板推导适用于数组,您需要将参数作为对数组的引用。

wstr(const wchar_t (&source)[sz]) { ... }
Run Code Online (Sandbox Code Playgroud)

  • @pink 告诉你的编译器使用 C++17。我盯着你的代码,修改为使用那里的参考,然后编译。 (2认同)