【问题标题】:size deduction in a templated c-string wrapper模板化 c 字符串包装器中的大小扣除
【发布时间】:2021-02-20 13:23:09
【问题描述】:

为什么这不起作用:

#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;
}

L"Hello" 已知是const wchar_t[6]

【问题讨论】:

  • source 的类型是 wchar_t const *,而不是数组,即使它被声明为一个。

标签: c++ arrays template-argument-deduction


【解决方案1】:

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

wstr(const wchar_t (&source)[sz]) { ... }

【讨论】:

  • 看起来不错,但仍然无法编译 - 没有推断出大小。
  • @pink 告诉你的编译器使用 C++17。我盯着你的代码,修改为在那里使用引用,然后编译。
  • 大概就是这样(使用 C++14)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多