简体   繁体   中英

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:-

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" . This is reasonable because the arguments I am passing are deduced to const char[6] and 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

The main confusion underlies in the value of L1 and L2. How compiler knows that it has to pass 6 and 7 to the template parameter L1 and 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. The length of the array is 6. As you can see, the length of the array is part of the type of the array. 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.

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(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM