[英]How std::size_t is calculated in the template code for array type
I was reading the book C++ templates - the complete guide, 2nd edition and got the code from that which looks like this:- 我正在阅读《 C ++模板 》一书-完整指南,第二版,并从中获得了如下代码:
template<typename T>
void showVal(const T &arg1, const T &arg2)
{
std::cout << arg1 << arg2;
}
int main() {
showVal("hello", "world1");
return 0;
}
The above code gave me this error:- "error C2782: 'void showVal(const T &,const T &)': template parameter 'T' is ambiguous" . 上面的代码给了我这个错误:- “错误C2782:'void showVal(const T&,const T&)':模板参数'T'不明确” 。 This is reasonable because the arguments I am passing are deduced to const char[6] and const char[7].
这是合理的,因为我传递的参数被推导为const char [6]和const char [7]。 To fix this, I have made the changes in the function which look like this after the change :-
为了解决这个问题,我对函数进行了如下更改:-
template<typename T, std::size_t L1, std::size_t L2>
void showVal(const T (&arg1)[L1], const T(& arg2)[L2])
{
std::cout << arg1 << arg2;
}
PS:- I've got this fix from the book PS:-我从书中获得了此修复程序
The main confusion underlies in the value of L1 and L2. 主要的困惑在于L1和L2的值。 How compiler knows that it has to pass 6 and 7 to the template parameter L1 and L2.
编译器如何知道它必须将6和7传递给模板参数L1和L2。 Is there any rule for array type.
数组类型有任何规则吗?
The type of "hello"
is const char[6]
, as shown in the error message of your first attempt. 如您首次尝试的错误消息所示,
"hello"
的类型为const char[6]
。 The length of the array is 6. As you can see, the length of the array is part of the type of the array. 数组的长度为6。如您所见,数组的长度是数组类型的一部分。 Since the compiler has to know the type, it implicitly also knows the length.
由于编译器必须知道类型,因此它隐式也知道长度。
Just like the template type argument T
was deduced to be const char
based on the type of the expressions passed to the non-template arguments arg1
and arg2
(those types being const char[6]
and const char[7]
), so too the template non-type arguments L1
and L2
were deduced from those same parameter types. 就像根据传递给非模板参数
arg1
和arg2
的表达式的类型(这些类型为const char[6]
和const char[7]
)将模板类型参数T
推导出为const char
,模板非类型参数L1
和L2
是从那些相同的参数类型推导出来的。
function template 功能模板
template<typename T, std::size_t L1, std::size_t L2>
void showVal(const T (&arg1)[L1], const T(& arg2)[L2])
for call showVal("hello", "world1") compiler will make implicit instantiation 调用showVal(“ hello”,“ world1”)编译器将进行隐式实例化
showVal(const char (&arg1)[6], const T(& arg2)[7])
and that is the way you can prevent that array decays to pointer, binding reference to array type, you achieve that array size of arguments is known to function definition. 这样便可以防止数组衰减到指针,将引用绑定到数组类型,从而实现函数定义已知参数的数组大小。 so for call showVal("hello", "world1"), compiler deduced T is char and arguments type are array of char size 6 and 7 respectively.
因此,对于调用showVal(“ hello”,“ world1”),编译器推断出T为char,而参数类型分别为char大小为6和7的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.