C++ 模板整数参数构造函数
我不理解下面的构造函数(src\corelib\tools\qstringbuilder.h中Qt库的一部分),它是什么意思,它是如何工作的C++ 模板整数参数构造函数,c++,templates,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 (&
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;
};
QLatin1Literal类
{
公众:
int size()常量{返回m_size;}
const char*data()const{return m_data;}
模板
Qlatin1文件(常量字符(&str)[N])
:m_大小(N-1),m_数据(str){}
私人:
const int mu size;
常量字符*常量m_数据;
};
这意味着str
是对N
常量字符数组的引用。它只是意味着构造函数将一个字符数组作为参数,例如字符串文字。构造函数将字符串文字作为参数。您所看到的只是一个用于为此声明模板的语法
使用这种构造函数,可以在O(1)中找到m_size,而不是使用以char const*
为参数的非模板构造函数所需的O(strlen(str))
需要记住的一点是,对于每个字符串长度,编译器将生成一个模板实例,因此您可能会在库/二进制/对象文件中有相当多的该模板实例。构造函数参数是对
N
字符数组的引用。它初始化m_data
以指向第一个字符,并将m_size
初始化为小于数组大小的一个字符
字符串文字,如“hello”
,是包含字符串中字符的数组,后跟零值终止符。因此,如果使用以下方法之一调用构造函数:
QLatin1Literal lit("hello");
assert(lit.size() == strlen("hello")); // SUCCESS: m_size is inferred as 5
它将推断N
的值为6(因为数组包含五个字符“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
N这是一个非类型模板参数。+1,但我想说这些“实例化”实际上是内联的,从来没有真正作为独立的形式进入二进制文件。@Andrew-同意,内联的影响只会略微增加编译时间,而不是二进制文件的大小。这里需要记住的另一件重要事情是由于特殊的大小写,当出现
const char*
重载时,将选择该重载,而不是模板重载,即使它看起来更匹配(无需衰减)。