c++ - 不允许类型名称

标签 c++ templates boost-spirit-qi

<分区>

我正在编写一个解析器,我正在尝试插入一个迭代器作为模板。 当我写 template<typedef class Iterator = std::string::iterator>代码按预期编译。我想我应该可以删除默认值,所以我想写 template<typedef class Iterator> .我认为这应该没问题,因为我稍后专门研究了模板。然而,这不会编译错误:Error (active) type name is not allowed .

这是怎么回事?为什么会出现此错误?

这里是示例代码:

#include <string>
#include <boost\spirit\include\qi.hpp>

namespace qi = boost::spirit::qi;

template<typedef class Iterator>  //<-- This does not compile
//template<typedef class Iterator = std::string::iterator>  //<-- This would compile
class Rules_template
{
private:
    typedef qi::rule<Iterator> skipper_rule;
    typedef qi::rule<Iterator> line_rule;
    typedef qi::rule<Iterator, std::string(), skipper_rule> string_rule;
    typedef qi::rule<Iterator, float, skipper_rule> float_rule;
    line_rule endofline = qi::lit("\r\n") | qi::lit("\n\r") | qi::lit('\n');
    skipper_rule skip = qi::lit(' ') | qi::lit('\t') | qi::lit('\f') | qi::lit('\v') | (qi::lit('\\') >> endofline);
    string_rule comment = qi::lexeme['#' >> *(qi::char_ - qi::char_('\n') - qi::char_('\r')) >> endofline];
public:
    string_rule & Comment() { return comment; }
    skipper_rule & Skip() { return skip; }
};

static Rules_template<std::string::iterator> Rules_str;

void CHECK(bool b)
{
    if (b)
        std::cout << "check ok" << std::endl;
    else
        std::cout << "check not ok" << std::endl;
}

int main(int argc, char ** argv)
{
    std::string test = "#This is a comment\n";
    std::string expect = "This is a comment";
    std::string actual;
    auto it = test.begin();
    CHECK(true == qi::phrase_parse(it, test.end(), Rules_str.Comment(), Rules_str.Skip(), actual));
    CHECK(it == test.end());
    CHECK(expect.compare(actual) == 0);
}

编辑 1:

这可能是特定于编译器的。我在使用 VS2015 时遇到此错误。

最佳答案

当我使用 Code::Blocks 编译器编译此代码时,出现此错误:

typedef declaration invalid in parameter declaration

当我将模板声明更改为:

template<class Iterator>

代码编译(0 个错误,0 个警告)并能够执行。

模板声明更改为时的相同结果:

template<class Iterator = std::string::iterator>

代码编译(0 个错误,0 个警告)并能够执行。

两种情况下的执行都会产生以下输出:

check ok
check ok
check ok

关于c++ - 不允许类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34705148/

相关文章:

c++ - 提升精神合成属性困惑

c++ - 是否有 boost::phoenix::at_c 结合 boost::spirit::qi::grammar 的替代方案

c++ - 头文件更改时,Visual Studio 2019 未构建所有 cpp 文件

c++ - 检测 IBeam 光标

c++ - 模板函数调用类中的 protected 方法?

c++ - 仅当没有其他转换可用时如何启用构造函数模板?

boost-spirit - 检索 token_def<> 的 ID

c++ - GLSL 点积问题

C++ 将 'this' 指针传递给基类然后将其存储为子类的另一个基类的预期行为是什么

c++ - template 模板参数,算作一个单独的参数