C++ 模板中依赖类型的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2931345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:31:50  来源:igfitidea点击:

Trouble with dependent types in templates

c++templatessyntaxstl

提问by Nick Heiner

I'm having trouble with templates and dependent types:

我在使用模板和依赖类型时遇到问题:

namespace Utils
{
    void PrintLine(const string& line, int tabLevel = 0);
    string getTabs(int tabLevel);

    template<class result_t, class Predicate>
    set<result_t> findAll_if(typename set<result_t>::iterator begin, set<result_t>::iterator end, Predicate pred) // warning C4346
    {
        set<result_t> result;
        return findAll_if_rec(begin, end, pred, result);
    }
}

namespace detail
{
    template<class result_t, class Predicate>
    set<result_t> findAll_if_rec(set<result_t>::iterator begin, set<result_t>::iterator end, Predicate pred, set<result_t> result)
    {
        typename set<result_t>::iterator nextResultElem = find_if(begin, end, pred);
        if (nextResultElem == end)
        {
            return result;
        }
        result.add(*nextResultElem);

        return findAll_if_rec(++nextResultElem, end, pred, result);
    }
}

Compiler complaints, from the location noted above:

编译器投诉,来自上述位置:

warning C4346: 'std::set<result_t>::iterator' : dependent name is not a type. prefix with 'typename' to indicate a type
error C2061: syntax error : identifier 'iterator'

What am I doing wrong?

我究竟做错了什么?

回答by James McNellis

Well, the warning says:

好吧,警告说:

dependent name is not a type. prefix with 'typename' to indicate a type

依赖名称不是类型。带有“typename”的前缀以指示类型

The dependent name (that is, the iteratorin std::set<result_t>::iterator) is not a type. You need to prefix it with typenameto indicate a type:

依赖名称(即iteratorin std::set<result_t>::iterator)不是类型。您需要在它前面加上前缀typename以指示类型:

typename std::set<result_t>::iterator

So, your declaration should be:

所以,你的声明应该是:

template<class result_t, class Predicate>
set<result_t> findAll_if(typename set<result_t>::iterator begin, typename set<result_t>::iterator end, Predicate pred)
                                                note added typename ^

(and the definition should match the declaration)

(并且定义应与声明匹配)

回答by GBegen

You need an additional typename keyword on this line:

在这一行你需要一个额外的 typename 关键字:

set<result_t> findAll_if(typename set<result_t>::iterator begin,typenameset<result_t>::iterator end, Predicate pred) // warning C4346

set<result_t> findAll_if(typename set<result_t>::iterator begin,类型名称set<result_t>::iterator end, Predicate pred) // warning C4346