lundi 30 juillet 2018

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 compare(const T &arg1, const T &arg2)
{
    std::cout << arg1 << arg2;
}

int main() {
    compare("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.

Aucun commentaire:

Enregistrer un commentaire