模板整数参数构造函数

Fre*_*red 10 c++ templates

我不明白以下构造函数(src\corelib\tools\qstringbuilder.h中的Qt库的一部分),它是什么意思,它是如何工作的?

class QLatin1Literal
{
public:
    int size() const { return m_size; }
    const char *data() const { return m_data; }

    template <int N>
    QLatin1Literal(const char (&str)[N])
        : m_size(N - 1), m_data(str) {}

private:
    const int m_size;
    const char * const m_data;
};
Run Code Online (Sandbox Code Playgroud)

bob*_*bah 11

构造函数将字符串文字作为参数.你看到的只是为此声明模板的语法.

使用这样的构造函数,m_size可以在O(1)中找到,与O(strlen(str))相反,否则需要非模板构造函数char const*作为参数.

需要记住的是,对于每个字符串长度,将有一个由编译器生成的模板实例,因此您最终可能会在库/二进制文件/目标文件中对此模板进行相当多的实例化.


Mik*_*our 8

构造函数参数是对N字符数组的引用.它初始化m_data为指向第一个字符,并且m_size小于数组的大小.

字符串文字就像"hello"是一个包含字符串中字符的字符数组,后跟一个零值终止符.因此,如果使用以下方法之一调用构造函数:

 QLatin1Literal lit("hello");
 assert(lit.size() == strlen("hello"));  // SUCCESS: m_size is inferred as 5
Run Code Online (Sandbox Code Playgroud)

它将推断值为6 N(因为数组包含五个字符"hello",加上终止符),并初始化m_size为5(实际字符串长度).

请注意,如果数组实际上不是字符串文字,这可能会出错; 例如:

char buffer[1000] = "hello";  // array size is larger than string+terminator
QLatin1Literal lit(buffer);
assert(lit.size() == strlen("hello"));  // FAIL: m_size is inferred as 999
Run Code Online (Sandbox Code Playgroud)