1

I'm trying to define a function using template template parameters (I just want to know how it works). I have the following:

template <typename T, template <typename> class Cont>
typename Cont<T>::iterator binary_search (typename Cont<T>::iterator first, typename Cont<T>::iterator last)
{
    typename Cont<T>::iterator it;
    // ...
    return it;
}

Then in the main () function:

std::vector<int> data;

// ....

std::vector<int>::iterator it = binary_search (data.begin (),data.end ());

I get this error when trying to compile the code:

binary_search.cpp: In function ‘int main(int, char**)’:
binary_search.cpp:43:83: error: no matching function for call to ‘binary_search(std::vector<int>::iterator, std::vector<int>::iterator)’

I cannot find any appropriate response that helps me to sort out this error. Any help would be appreciated.

Thanks in advance

user1192525
  • 657
  • 4
  • 20

1 Answers1

2

What you have is a non-deduced context, aswell as a template template parameter mismatch even if the context was deducible. std::vector takes a second template parameter, the allocator, that is defaulted to std::allocator.

For the non-deduced context, T can never be deduced and will always have to be specified, the typename indicates this. See this question for the gory details.

Community
  • 1
  • 1
Xeo
  • 129,499
  • 52
  • 291
  • 397
  • Hi, thanks very much for the clarification. Is there any way to work around the parameter mismatch? (and thanks also for the link, it's really useful) – user1192525 Apr 08 '12 at 12:09
  • Just template on the iterators, that's all you need. `template // done`. – Xeo Apr 08 '12 at 12:12
  • Yep, finally I had a look at the STL header files and did it that way: ` template bool binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) ` – user1192525 Apr 08 '12 at 12:36
  • @user: No, no, and *no*. Don't use `_This` or `__this` naming convention, it's reserved by the standard for the implementation. Just drop the underscores. – Xeo Apr 08 '12 at 13:34
  • I didn't use them, just copied & pasted from the STL header file :) – user1192525 Apr 08 '12 at 15:26
  • @user: Oh, okay, then nevermind. But using such a naming convention is one of my pet-peeves. :) – Xeo Apr 08 '12 at 15:43