example (regex.cpp)에서 라이브러리 작성자는 custom struct (magic_number) 및이 struct에 대한 유효성 검사 함수를 작성하여 사용자 정의 struct를 프로그램 옵션에 통합하는 방법을 보여줍니다. 그의 예제를 따라 사용자 정의 클래스 (MyClass)에 대한 유효성 검사 함수를 작성했습니다. 컴파일러는 MyClass에 lexical_cast를 사용할 수 없다고 불평합니다. 그런 다음 std::istream& operator>>(std::istream& in, MyClass& d)
을 구현하고 void validate(.., MyClass*, ..)
을 제거하면 코드가 컴파일됩니다. 누구든지 operator>>
을 필요로하지 않는 이유를 설명 할 수 있습니까? 광산에는 validate
이 필요하지 않습니다.프로그램 옵션 올리기 : 사용자 정의 유효성 검사기에 과부하 연산자가 필요합니까 >>?
편집 :
#include <MyLib/MyClass.h>
std::istream& operator>>(std::istream& in, MyClass& obj) {
// some code to populate obj
return in;
}
po::variables_map parseCommandLine(int argc, char* argv[]) {
po::options_description options("Options");
options.add_options()
("help", "produce help message")
("obj", po::value<MyClass>(), "")
;
po::variables_map vm;
store(po::command_line_parser(argc, argv)
.options(options).run(), vm);
notify(vm);
return vm;
}
int main(int argc, char* argv[]) {
try {
po::variables_map vm = parseCommandLine(argc, argv);
MyClass obj = vm["my"].as<MyClass>();
cout << obj << endl;
} catch(std::exception& e) {
cout << e.what() << "\n";
return 1;
}
return 0;
}
- 코드의 유효성을 검사하지 않고 컴파일합니다.
- 제거 magic_number
- 이
#include <MyLib/MyClass.h>
- 가 MyClass에 의해 magic_number의 모든 occurance을 대체 추가
는 또한 regex.cpp에 최소한의 변경을 시도했다.
편집 : validate
을 추가하십시오. 그들 중 누구도 컴파일러 오류를 해결하지 못했습니다.
void validate(boost::any& v,
const std::vector<std::string>& values,
std::vector<MyClass>*, int)
{
}
void validate(boost::any& v,
const std::vector<std::string>& values,
MyClass*, long)
{
}
void validate(boost::any& v,
const std::vector<std::string>& values,
MyClass*, int)
{
}
편집 : 이것은 네임 스페이스와 관련 될 수 있습니다.
유효성 검사 기능을 namespace boost { namespace program_options { }}
으로 묶은 후에 코드에 op >>이 (가) 오버로드되지 않고 컴파일되었습니다. 또한 유효성 검사가 MyClass와 동일한 네임 스페이스에 추가 된 경우에도 작동합니다. 아무도 이것을 설명 할 수 있습니까?
'program_options' 객체를 어떻게 선언했는지 볼 수 있습니까? 유효성 검사가 없다면'op >>'없이 객체를 파싱 할 방법이 없다. –
이것은 컴파일러 문제입니다. http://stackoverflow.com/questions/13501598/c-the-context-of-an-unqualified-name-lookup- : [여기에 문제의 설명] [1] [1] 참조 in-a-template –