1
我在編寫boost::spirit::qi
規則時偶然發現了這個。我寫了一個不正確的規則聲明,我通過添加括號來修復。我想到我不知道爲什麼這會有所作爲。'char()'和'char'在C++中有什麼區別
char
和char()
有什麼區別?
這是一個最小的例子,顯示這將是相關的。
測試A
和B
是等同的。測試C
編譯但未通過測試。 測試D
被註釋掉,不會編譯消息:C2440: 'static_cast' : cannot convert from 'skipper_type' to 'char'
。 (使用稍微複雜的類型,錯誤將爲C2664
)
該測試示例僅用於說明使用char
與char()
有何不同。我的問題是兩者之間的差異。
#include <iostream>
#include <string>
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <boost/spirit/include/qi.hpp>
using std::string;
namespace qi = boost::spirit::qi;
using Iterator = std::string::iterator;
using Skipper = qi::space_type;
Skipper skipper = qi::space;
void CHECK_ITERATOR(Iterator p, Iterator end)
{
if (p != end)
{
BOOST_CHECK_MESSAGE(p == end, "Remaining: " << string(p, end));
}
}
BOOST_AUTO_TEST_CASE(parse_char_type_B)
{
qi::rule<Iterator, Skipper, char()> rule = qi::char_;
char expected = 'B';
char actual = 0;
string toParse(&expected, (&expected) + 1);
Iterator it = toParse.begin();
BOOST_REQUIRE(qi::phrase_parse(it, toParse.end(), rule, skipper, actual));
CHECK_ITERATOR(it, toParse.end());
BOOST_CHECK_EQUAL(expected, actual);
}
BOOST_AUTO_TEST_CASE(parse_char_type_C)
{
qi::rule<Iterator, Skipper, char> rule = qi::char_;
char expected = 'C';
char actual = 0;
string toParse(&expected, (&expected) + 1);
Iterator it = toParse.begin();
BOOST_REQUIRE(qi::phrase_parse(it, toParse.end(), rule, skipper, actual));
CHECK_ITERATOR(it, toParse.end());
BOOST_CHECK_EQUAL(expected, actual);
}
BOOST_AUTO_TEST_CASE(parse_char_type_D)
{
//qi::rule<Iterator, char, Skipper> rule = qi::char_;
char expected = 'D';
char actual = 0;
string toParse(&expected, (&expected) + 1);
Iterator it = toParse.begin();
//BOOST_REQUIRE(qi::phrase_parse(it, toParse.end(), rule, skipper, actual));
//CHECK_ITERATOR(it, toParse.end());
//BOOST_CHECK_EQUAL(expected, actual);
}
注意,根據上下文,'char()'也可以是一個初始化值爲'char'的對象。 – Angew
@Angew當然,補充說明一下。 – TartanLlama