2016-01-10 169 views
-1

我正在寫一個解析器,我試圖插入一個迭代器作爲模板。 當我編寫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); 
} 

EDIT 1:

這可能是編譯器具體。 VS2015出現這個錯誤。當我更改模板聲明

typedef declaration invalid in parameter declaration 

template<class Iterator> 

代碼編譯(0失誤,0

+6

'模板'肯定是在標準C語法錯誤++。你確定這是原始代碼嗎? – cpplearner

+4

你的意思是使用'typename'? –

+0

看到這裏的例子http://en.cppreference.com/w/cpp/language/template_parameters – user3159253

回答

4

當我編譯使用代碼:: Blocks的編譯器的代碼,我得到這個錯誤警告)並且能夠執行。

同樣的結果,當模板聲明更改爲:

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

代碼編譯(0個錯誤,0警告),並能夠執行。

執行在這兩種情況下會產生以下輸出:

check ok 
check ok 
check ok