I am struggling a bit with templates; I am trying to write a method that iterates over a range of strings, no matter their type or the container they are kept in. In the following code:

template<template<class> class ContainerType,
         typename CharType>
ContainerType<basic_string<CharType>>
foo(typename ContainerType<basic_string<CharType>>::iterator begin,
    typename ContainerType<basic_string<CharType>>::iterator end,
    CharType letter)
{
    return ContainerType<basic_string<CharType>>();
}

int main()
{
    vector<string> words;
    auto bar = foo(words.begin(), words.end(), 'a');
}

The compiler can't figure out the type of ContainerType. I must say that I am a beginner when it comes to C++ templates.

有帮助吗?

解决方案

Simply speaking, template argument type deduction only works to the right of the last ::, if there is one. Imagine what you're telling the compiler:

I am calling foo() with a certain type. Now I want you to look at all single-parameter class templates which could possibly exist, try to instantiate each of them with all possible types, and see for which of these a nested typedef iterator matches the type I sent to foo. Then use that combination as template arguments.

I believe it's pretty obvious that doesn't work. That's why anything to the left of :: is a non-deduced context, so template parameters in such context don't participate in template argument deduction. And since foo offers no other context, the argument cannot be deduced.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top