Mar 24, 2011

C++ Error: No Matching Function call Template Edition

No you're not having deja-vu. It's the same error message but with a completely different cause.

What the compiler actually said

no matching function for call to 'TodTest::TestClass::SendVectorToCout(std::vector<int, std::allocator<int> >&, bool) const'    TestClass.cpp   
I used this because it involves both a template and a vector. The vector message can be confusing to begin with because you can easily forget that vector<T> really turns into vector<T, std::allocator<T> > so you want to avoid chasing that particular red herring.

 

What the compiler was too polite to say

For Frack's sake if you're going to call a template and I can't deduce the types from the arguments would please stop being an idjit and supply them for me? Huh, would ya?
This doesn't make too much sense until you see the code. Now I make this mistake about once a day so I figure someone else is bound to make it at least every now and then. When I first write a template I know exactly how to use it. A day or so later, maybe not so much

SNAGHTMLbee8cf1

The point of having T1 and T2 is expressly for things like vector<byte>. If the vector contains binary data it prints out as gobbledygook unless you cast it as something like short. (The reason is in C++ a byte is really just an unsigned char and cout thinks an unsigned char should be displayed as a char). So if you want to see the integer value instead you cast it as a short. Now I realize I could specialize the template and make it easier to use but you'll run into your own lazy template one of these days so consider this a learning example. If we had default function template arguments I would be tempted to default T2=T1, but until c++1x is out...

 

Making the Compiler Happy

This means even if you have a vector of ints you want to display as ints you can't call this template with code like this:

image

Instead you need to do this:

SNAGHTMLbf42920

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.