문제

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