반응형

Kevlin Henney

소개
예제
참고문서
값 타입 조건들
헤더 <boost/any.hpp>
감사인사

소개

일반적인( 템플릿 기반 프로그래밍에 대조되는 일반적인 의미에서) 타입이 필요합니다

: 실로 변하기 쉬운 변수들, 일반의 엄밀한 그리고 정적인 타입들보다 많은 다른 더 구체적인 타입들의 값에 부합하는 것.

우리는 일반적인 타입의 3가지 기본 종류들을 구분할 수 있습니다.

  • 가능한 값 타입들(예를들면 int 와 string)의 다수중 하나를 유지할 수 있는 변환하는 타입들, 그리고 자유롭게 그들 사이에서 자유롭게 변한다. (예를들면 5 를 "5" 또는 그반대의 경우도 해석하는것)
    그러한 타입들은 스크립팅과 그밖의 해석되어지는 언어 안에서 공통입니다.
    boost::lexical_cast 는 그러한 변환 기능을 제공한다.

  • 다른 타입들의 값 그러나 그들(즉 5는 "5" 또는 5.0 둘중 한쪽으로 절대 변환되어지 않고 int 로서 정확하게 유지된다 )
    사이에서 변환을 시도하지 않는 구별되는 타입들.
    단일값들의 일반적인 컨테이너들, 타입의 인지를 제외하고 해석에 대해 그것들의 동작없음은 그것들을 해석이가능한 변환으로부터 얘기치 않은 일에대해 범위없이 효과적으로 안전하게합니다.

  • 접근과 프로그래머에 대한 해석의 모든 형태들을 맡기면서, 무엇이든 참조할수있는 하지만 실제 기본 타입에대해 염두하지 않는 분간없는 타입들.
    이 일은 void* 에 의해 지배되어집니다 그것은 얘기치 않은 일, 분명하지 않은 행동에 대한 범위의 다량을 줍니다.

( C++ Report 12(7), July/August 2000, Kevlin Henney에 의해 "높이평가되는 변환들" 에서 설명되어진 같은 이름들의 클래스에 기초로되어진)

boost::any 클래스는 두번째 범주에 기반되는 변하기 쉬운 값 타입입니다.

boost::any는 어떤 값 타입과 boost::any의 타입에 정확하게 반대되는 어떤 값의 안전 점검된 추출의 복사를 지원합니다.

더 많은 적절한 연산들을 제공하기때문에, 유사한 디자인은 일반적인 함수 어뎁터(adaptor),any_funtion, 일반적인 iterator adaptor, any_iteator, 그리고 균일한 런타임 처리를 필요로하는 다른 오브젝트 타입들에 사용할수있습니다.

최근 2009 7월 26일, at 21:11:03 +0100 에 수정되었습니다.


예제

다음의 코드는 어떤 오브젝트들의 암시적 변환과 복사를 사용하는 것에 대해 문법을 설명합니다 :


#include <list>
#include <boost/any.hpp>

using boost::any_cast;
typedef std::list<boost::any> many;

void append_int(many & values, int value)
{
    boost::any to_append = value;
    values.push_back(to_append);
}

void append_string(many & values, const std::string & value)
{
    values.push_back(value);
}

void append_char_ptr(many & values, const char * value)
{
    values.push_back(value);
}

void append_any(many & values, const boost::any & value)
{
    values.push_back(value);
}

void append_nothing(many & values)
{
    values.push_back(boost::any());
}

다음은 이전 정의들로부터 흐름을 설명하고 어떤 오브젝트들에 대한 조건들의 사용을 설명합니다 :

bool is_empty(const boost::any & operand)
{
    return operand.empty();
}

bool is_int(const boost::any & operand)
{
    return operand.type() == typeid(int);
}

bool is_char_ptr(const boost::any & operand)
{
    try
    {
        any_cast<const char *>(operand);
        return true;
    }
    catch(const boost::bad_any_cast &)
    {
        return false;
    }
}

bool is_string(const boost::any & operand)
{
    return any_cast<std::string>(&operand);
}

void count_all(many & values, std::ostream & out)
{
    out << "#empty == "
        << std::count_if(values.begin(), values.end(), is_empty) << std::endl;
    out << "#int == "
        << std::count_if(values.begin(), values.end(), is_int) << std::endl;
    out << "#const char * == "
        << std::count_if(values.begin(), values.end(), is_char_ptr) << std::endl;
    out << "#string == "
        << std::count_if(values.begin(), values.end(), is_string) << std::endl;
}

OMG의 property 서비스를 본떠서 만들어 졌기때문에, 타음의 타입들은 임의의 값 타입들에 대해 name-value 쌍들을 정의합니다 :

struct property
{
    property();
    property(const std::string &, const boost::any &);

    std::string name;
    boost::any value;
};

typedef std::list<property> properties;

다음의 기본 클래스는 임의의 인자 타입들 또한 필요로하는 콜벡들에 기반을 둔 런타임 다형성에 하나의 접근을 설명합니다 :

class consumer
{
public:
    virtual void notify(const any &) = 0;
    ...
};



참고문서

ValueType 필요조건들

값들(values)은 독자성이 중요하지 않은 견고한 정보의 오브젝트들이다, 즉 주안점은 대게 그것들의 상태와 그것들 주위에

조직화된 행동이다.

값들에 대해 또 하나의 구별되는 특징은 그것들의 단위이다:

예를들자면 보통은 다수와 같은 시스템안에서 간단한 개념들을 나타내는 조직적인 오브젝트들이다

한 값의 주안점은 그것의 상태안에 놓여있는것으로 그것은 독립성이 아니다,

값들이 복사되어질수 있고 대체적으로 다른것에서 하나가 할당 되어질수 있다,

public 복사생성자와 public 할당 operator의 명시적 또는 묵시적 정의를 필요로 하면서...

값들은 힙에 보다는 대체로 다른 범위들 즉 오브젝트들 또는 블럭들 내부에 남아있다

값들은 그러므로 보통 전달되어지고 곧장 조작되어진다 값들 또는 참조를 통함으로서...

하지만 독립성과 간접적인 방법을 잘 나타내는 포인터로서가 아닌..

any 에 사용되어지기 위한 값타입들에 대한 구체적인 필요조건이다 :

  • ValueType 은 복사생성되어진다[20.1.3].
  • ValueType 은 선택적으로 할당되어진다[23.1]. 강한 예외안전보장은 할당의 모든형태들에 필요하다.
  • ValueType에 대한 파괴자는 예외를던지지않는 예외안정보장성을 유지시킨다.

Header <boost/any.hpp>

namespace boost {
  class bad_any_cast;
  class any;
  template<typename T> T any_cast(any &);
  template<typename T> T any_cast(const any &);
  template<typename ValueType> const ValueType * any_cast(const any *);
  template<typename ValueType> ValueType * any_cast(any *);
}

Copyright © 2001 Kevlin Henney

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)



번역된 원문 http://www.boost.org/doc/libs/1_51_0/doc/html/any.html

http://www.boost.org/doc/libs/1_51_0/doc/html/any/s02.html

반응형
반응형

Eric Niebler

저작권 © 2005, 2006 Eric Niebler

Boost 소프트웨어 라이센스에 의해 배포되어졌다(참부파일을 보세요 LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

목록

서문

사용자의 가이드
Accumulators 프레임워크
통계의 Accumulators 라이브러리
감사의 글
참고사항
Accumulators 프레임워크 참고문서
통계적 라이브러리 참고문서
수 연산들 라이브러리 참고문서

서문

정확히 잘못된 것 보다 대략 맞는게 더 낫다

-- 속담

설명

Boost.Accumulators 는 대체적으로 증분 계산을 위한 확장가능한 프레임워크 분만 아니라 증분 통계 계산을 위한 라이브러리 입니다

라이브러리는 accumulator 의 개념을 주로 취급합니다 그리고 accumulator 는 몇몇의 내부상태를 유지하고 한번에 데이터 한 샘플을 받아들이는 기본 계산에관한 엔티티입니다.

이 accumulators는 다른 accumulators에 있는 그들의 계산 몇몇을 떠남길지도 모른다 그리고 다른 accumulators를 accumulators가 의존합니다

Accumulators 는 accumulator 세트 하나와 함께 그룹화되어집니다.

Boost.Accumulators는 한 세트안의 accumulators 와 accumulators가 적절한 명령에서 처리되어지는 것을 보장하는 것 사이에서

상호의존성을 해결합니다

최근 2010년 8월 15일at 23:42:55 GMT 에 수정되었습니다.


유저 가이드

이 섹션은 새로운 accumulators를 생성하기위한 Boost.Accumulators 프레임워크를 사용하는 방법 그리고 증분 통계적 계산을

수행하기 위한 존재하는 통계적 accumulators를 사용하기 위한 방법을 설명합니다

Boost.Accumulators에 구체적인 구성요소에 관한 상세한 정보를 위해서, Reference 섹션을 확인하세요

Hello, World!

아래에 Accumulators 프리엠워크를 사용하는 방법과 증분 통계적 계산을 수행하기 위한 통계적 Accumulators에 대한 완전한 예제가 있습니다.

그것은 평균과 더블(doubles)의 시퀀스에대한 2nd moment(통계학 용어) 를 계산합니다.

#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
using namespace boost::accumulators;

int main()
{
    // 2nd moment와 평균을 계산하는 것을 위한 accumulator 세트를 정의합니다
accumulator_set<double, stats<tag::mean, tag::moment<2> > > acc; // 몇몇의 데이터를 넣습니다 ... acc(1.2); acc(2.3); acc(3.4); acc(4.5); // 결과를 보여줍니다 ... std::cout << "Mean: " << mean(acc) << std::endl; std::cout << "Moment: " << accumulators::moment<2>(acc) << std::endl; return 0; }

이 프로그램은 다음을 보여줍니다:

Mean:   2.85
Moment: 9.635

* 이하 보류(0)


번역된 원문

http://www.boost.org/doc/libs/1_51_0/doc/html/accumulators.html

http://www.boost.org/doc/libs/1_51_0/doc/html/accumulators/user_s_guide.html

반응형
반응형

이 문서는 오직 전체 부스트의 문서의 일부를 나타냅니다 : QuickBook 이나 BoostBook 소스 로부터 발생되어진 문서입니다

결국 모든 Boost 라이브러리들은 그것들의 포멧들을 사용할지도 모릅니다.

하지만 그동안에, Boost의 문서의 많은 양은 이곳에서 이용할 수 없습니다.

컴퓨터 문서를 위한 http://www.boost.org/libs 를 보세요.

이 문서안에 기술되어진 라이브러리들의 몇몇을 위한 문서는 선택적 포멧(아래 두개)들안에서 이용 가능합니다 :

Boost 원문 : http://www.boost.org/doc/libs/1_51_0/doc/html/about.html

반응형
반응형

번역자 : 3DMP 운영자

boost 버전 : Boost 1.51.0 Library

원본 : http://www.boost.org

목적 : study

용어 : boost 에서 정해져있는 영어 대명사등이 될법한 것들을 번역하지 않고 그대로 기제합니다

남기는 말 : 해석순서는 순차적으로 가지만 쓸만한것 위주로 번역하고 번역하지 않고 보류하는 것에 대해선

제목과 같이 써놓겠습니다.

틀린 번역이나 오타가 있다면 댓글 달아주시거나 글을 남겨주시면 참고하여 수정하도록 하겠습니다



[Boost 1.51.0 라이브러리 문서]

항목별로

문자와 문자 처리

  • Conversion: 다형성과 사전적 캐스트들.
  • Format: format 라이브러리는 foramt-string을 따라 아규먼트들을 포멧하기위한 클래스를 제공한다, printf가 제공하는것처럼,
    그러나 주요 차이점 :
    format 은 내부의 스트림으로 아규먼트들을 전달한다, 그리고 또한 온전히 타입이 안전하고 자연스럽게 모든 유저저의 타입들을 지원한다.
  • Iostreams: Boost.IOStreams은 정의되는 스트림, 스트림 버퍼와 입/출력 파일을 위한 프레임워크를 제공한다.
  • Lexical Cast: 일반적인 문자그대로의 텍스트 변환, int가 string을 나타내거나 또는 반대인경우, Kevlin Henney로부터...
  • Locale: 로컬리제이션과 C++을 위한 툴들을 취급하는 유니코드를 제공한다.
  • Regex: 정규표현식 라이브러리.
  • Spirit: LL 파서 프레임워크는 인라인된 C++안에서 EBNF 문법처럼 직접적으로 파서들을 나타낸다.
  • String Algo: String 알고리즘 라이브러리.
  • Tokenizer: string또는 토큰들의 나열로 다른 문자연속을 분리한다.
  • Wave: Boost.Wave 라이브러리는 표준 준수이고, C99/C++ 프로세서 기능성의 고도로 설정된 수행이 iterator 인터페이스를 사용하기 위해서 쉬운것을 넘어 포장되어있다.
  • Xpressive: string이나 expreesion 템플릿처럼 쓰여질수있는 정규표현식, 그리고 그것은(expression 템플릿)은 각각 다른것들 그리고
    그들과 context-free 문법의 힘을가지고 재귀적으로 그것자체들을 참조한다.

컨테이너들

  • Array: 상수 사이즈의 배열을 위한 STL 호환 컨테이너 래퍼.
  • Bimap: C++을 위한 양방향성의 map 라이브러리. Boost.Bitmap으로 당신은 양쪽 타입이 키 로서 사용되어질 수 있는 연관 컨테이너를 만들 수있다.
  • Circular Buffer: STL 준수 컨테이너는 링이나 순환버퍼로 또한 알려져있다.
  • Container: 표준라이브러리 컨테이너와 확장들.
  • Dynamic Bitset: dynamic_bitset 클래스는 비트의 세트를 나타낸다. 그것은 operator[] 를 거쳐 각각의 비트의 값으로 접근과 그리고
    본래의 정수들로 적용할 수 있는 비트에관한 operator들의 모든것을 제공한다, 예를들어 operator&와 operator<< 세트안의 숫자가 dynamic_bitset의 생성자에 파라미터를 가쳐 실행시간에 구체화되어지는것과 같이.
  • GIL: 일반적 이미지 라이브러리
  • Graph: BGL 그래프 인터페이스와 그래프 구성요소는 일반적이다, 같은 의미안에서 표준 템플릿 라이브러리(STL) 처럼.
  • ICL: 인터벌 컨테이너 라이브러리, 인터벌 세트들(sets) 그리고 맵들(maps)과 연관되어있는 값들의 집합
  • Intrusive: Intrusive 컨테이너들과 알고리즘들.
  • Multi-Array: Boost.MultiArray는 일반적은 N 차원적의 배열 컨셉정의와 그것(배열)의 인터페이스의 공통적 구현을 제공한다.
  • Multi-Index: Boost 멀티인덱스 컨테이너 라이브러리는 하나 또는 다른 정렬과 접근 의미를 가지고 더많은 인덱스들을 유지하는 컨테이너의 구조를 가능하게하는 multi_index_container로 지명된 클래스 템플릿을 제공한다.
  • Pointer Container: 객체지향적 프로그래밍을 용이하게 하기위해서 힙이할당된 다형성 오브젝트를 정렬을 위한 컨테이너.
  • Property Map: value 오브젝트로 키 오브젝트를 만든 인터페이스를 정의한 개념.
  • Property Tree: 환경설정 데이터를 정렬하는것에 특별히 적합한 트리 데이터구조.
  • Unordered: 정렬되지않은 연관 컨테이너.
  • Variant: 안전, 일반적, 스택 기반된 차별된 병합(union) 컨테이너.

이터레이터들

  • GIL: =(일반적인 이미지 라이브러리)
  • Graph: BGL 그래프 인터페이스와 그래프 구성요소는 일반적(포괄적)이다, 표준 템플릿 라이브러리(STL)로서 같은 의미안에서.
  • Iterators: Boost 이터레이터(Iterator) 라이브러리는 두가지를 포함한다. 첫번째는 C++ 표준 이터레이터 필요조건을 확장할수 있는 개념의 시스템이다. 두번째는 이 확장되어진 개념들로 기반되어진 이터레이터를 만들기위한 구성요소들의 프레임워크이다 그리고 몇몇의 유용한 이터레이터 어뎁터(adaptors)를 포함한다.
  • Operators: 템플릿은 산술클래스들과 이터레이터들을 용이하게한다.
  • Tokenizer: string 이나 토큰의 연속에서 다른 문자 시퀀스를 절단(분할)한다.

알고리즘들

  • Algorithm: 유용한 일반적 알고리즘들의 모임.
  • Foreach: In C++, writing a loop that iterates over a sequence is tedious. We can either use iterators, which requires a considerable amount of boiler-plate, or we can use the std::for_each() algorithm and move our loop body into a predicate, which requires no less boiler-plate and forces us to move our logic far from where it will be used. In contrast, some other languages, like Perl, provide a dedicated "foreach" construct that automates this process. BOOST_FOREACH is just such a construct for C++. It iterates over sequences for us, freeing us from having to deal directly with iterators or write predicates.
  • Geometry: Geometry Library.
  • GIL: Generic Image Library
  • Graph: The BGL graph interface and graph components are generic, in the same sense as the the Standard Template Library (STL).
  • Min-Max: Standard library extensions for simultaneous min/max and min/max element computations.
  • Range: A new infrastructure for generic algorithms that builds on top of the new iterator concepts.
  • String Algo: String algorithms library.
  • Utility: Class noncopyable plus checked_delete(), checked_array_delete(), next(), prior() function templates, plus base-from-member idiom.

함수 오브젝트들과 고차원 프로그래밍

  • Bind: boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.
  • Function: Function object wrappers for deferred calls or callbacks.
  • Functional: The Boost.Function library contains a family of class templates that are function object wrappers.
  • Functional/Factory: Function object templates for dynamic and static object creation
  • Functional/Forward: Adapters to allow generic function objects to accept arbitrary arguments
  • Functional/Hash: A TR1 hash function object that can be extended to hash user defined types.
  • Functional/Overloaded Function: Overload different functions into a single function object.
  • Lambda: Define small unnamed function objects at the actual call site, and more.
  • Local Function: Program functions locally, within other functions, directly within the scope where they are needed.
  • Member Function: Generalized binders for function/object/pointers and member functions.
  • Phoenix: Define small unnamed function objects at the actual call site, and more.
  • Ref: A utility library for passing references to generic functions.
  • Result Of: Determines the type of a function call expression.
  • Signals: Managed signals & slots callback implementation.
  • Signals2: Managed signals & slots callback implementation (thread-safe version 2).
  • Utility: Class noncopyable plus checked_delete(), checked_array_delete(), next(), prior() function templates, plus base-from-member idiom.

일반적인 프로그래밍

  • Call Traits: Defines types for passing parameters.
  • Concept Check: Tools for generic programming.
  • Enable If: Selective inclusion of function template overloads.
  • Function Types: Boost.FunctionTypes provides functionality to classify, decompose and synthesize function, function pointer, function reference and pointer to member types.
  • GIL: Generic Image Library
  • In Place Factory, Typed In Place Factory: Generic in-place construction of contained objects with a variadic argument-list.
  • Operators: Templates ease arithmetic classes and iterators.
  • Property Map: Concepts defining interfaces which map key objects to value objects.
  • Static Assert: Static assertions (compile time assertions).
  • Type Traits: Templates for fundamental properties of types.

템플릿 메타프로그래밍

  • Function Types: Boost.FunctionTypes provides functionality to classify, decompose and synthesize function, function pointer, function reference and pointer to member types.
  • Fusion: Library for working with tuples, including various containers, algorithms, etc.
  • MPL: The Boost.MPL library is a general-purpose, high-level C++ template metaprogramming framework of compile-time algorithms, sequences and metafunctions. It provides a conceptual foundation and an extensive set of powerful and coherent tools that make doing explict metaprogramming in C++ as easy and enjoyable as possible within the current language.
  • Proto: Expression template library and compiler construction toolkit for domain-specific embedded languages.
  • Static Assert: Static assertions (compile time assertions).
  • Type Traits: Templates for fundamental properties of types.

프로세서 메타프로그래밍

  • Identity Type: Wrap types within round parenthesis so they can always be passed as macro parameters.
  • Preprocessor: Preprocessor metaprogramming tools including repetition and recursion.

동시(병행) 프로그래밍

  • Asio: Portable networking, including sockets, timers, hostname resolution and socket iostreams.
  • Context: Context switching library.
  • Interprocess: Shared memory, memory mapped files, process-shared mutexes, condition variables, containers and allocators.
  • MPI: Message Passing Interface library, for use in distributed-memory parallel application programming.
  • Thread: Portable C++ multi-threading.

수학과 수치(수)

  • Accumulators: Framework for incremental calculation, and collection of statistical accumulators.
  • Geometry: Geometry Library.
  • Integer: The organization of boost integer headers and classes is designed to take advantage of <stdint.h> types from the 1999 C standard without resorting to undefined behavior in terms of the 1998 C++ standard. The header <boost/cstdint.hpp> makes the standard integer types safely available in namespace boost without placing any names in namespace std.
  • Interval: Extends the usual arithmetic functions to mathematical intervals.
  • Math: Boost.Math includes several contributions in the domain of mathematics: The Greatest Common Divisor and Least Common Multiple library provides run-time and compile-time evaluation of the greatest common divisor (GCD) or least common multiple (LCM) of two integers. The Special Functions library currently provides eight templated special functions, in namespace boost. The Complex Number Inverse Trigonometric Functions are the inverses of trigonometric functions currently present in the C++ standard. Quaternions are a relative of complex numbers often used to parameterise rotations in three dimentional space. Octonions, like quaternions, are a relative of complex numbers.
  • Math Common Factor: Greatest common divisor and least common multiple.
  • Math Octonion: Octonions.
  • Math Quaternion: Quaternions.
  • Math/Special Functions: A wide selection of mathematical special functions.
  • Math/Statistical Distributions: A wide selection of univariate statistical distributions and functions that operate on them.
  • Multi-Array: Boost.MultiArray provides a generic N-dimensional array concept definition and common implementations of that interface.
  • Numeric Conversion: Optimized Policy-based Numeric Conversions.
  • Operators: Templates ease arithmetic classes and iterators.
  • Random: A complete system for random number generation.
  • Ratio: Compile time rational arithmetic.
  • Rational: A rational number class.
  • uBLAS: uBLAS provides matrix and vector classes as well as basic linear algebra routines. Several dense, packed and sparse storage schemes are supported.

확성과 테스팅

  • Concept Check: Tools for generic programming.
  • Static Assert: Static assertions (compile time assertions).
  • Test: Support for simple program testing, full unit testing, and for program execution monitoring.

데이터 구조들

  • Any: Safe, generic container for single values of different value types.
  • Bimap: Bidirectional maps library for C++. With Boost.Bimap you can create associative containers in which both types can be used as key.
  • Compressed Pair: Empty member optimization.
  • Container: Standard library containers and extensions.
  • Fusion: Library for working with tuples, including various containers, algorithms, etc.
  • Heap: Priority queue data structures.
  • ICL: Interval Container Library, interval sets and maps and aggregation of associated values
  • Multi-Index: The Boost Multi-index Containers Library provides a class template named multi_index_container which enables the construction of containers maintaining one or more indices with different sorting and access semantics.
  • Pointer Container: Containers for storing heap-allocated polymorphic objects to ease OO-programming.
  • Property Tree: A tree data structure especially suited to storing configuration data.
  • Tuple: Ease definition of functions returning multiple values, and more.
  • Uuid: 일반적으로 유일한 식별자.
  • Variant: Safe, generic, stack-based discriminated union container.

영역 세부적인 특성

  • Chrono: 유용한 시간 유틸리티들.
  • CRC: The Boost CRC Library provides two implementations of CRC (cyclic redundancy code) computation objects and two implementations of CRC computation functions. The implementations are template-based.
  • Date Time: A set of date-time libraries based on generic programming concepts.
  • Units: Zero-overhead dimensional analysis and unit/quantity manipulation and conversion.
  • Uuid: 일반적으로 유일한 식별자.

이미지 프로세싱

  • GIL: 일반적 이미지 라이브러리

입/출력

  • Asio: Portable networking, including sockets, timers, hostname resolution and socket iostreams.
  • Assign: Filling containers with constant or generated data has never been easier.
  • Format: The format library provides a class for formatting arguments according to a format-string, as does printf, but with two major differences: format sends the arguments to an internal stream, and so is entirely type-safe and naturally supports all user-defined types; the ellipsis (...) can not be used correctly in the strongly typed context of format, and thus the function call with arbitrary arguments is replaced by successive calls to an argument feeding operator%.
  • IO State Savers: The I/O sub-library of Boost helps segregate the large number of Boost headers. This sub-library should contain various items to use with/for the standard I/O library.
  • Iostreams: Boost.IOStreams provides a framework for defining streams, stream buffers and i/o filters.
  • Program Options: The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.
  • Serialization: Serialization for persistence and marshalling.

상호간의 언어지원

  • Python: The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler.

언어 특징 에뮬레이션

  • Exception: The Boost Exception library supports transporting of arbitrary data in exception objects, and transporting of exceptions between threads.
  • Foreach: In C++, writing a loop that iterates over a sequence is tedious. We can either use iterators, which requires a considerable amount of boiler-plate, or we can use the std::for_each() algorithm and move our loop body into a predicate, which requires no less boiler-plate and forces us to move our logic far from where it will be used. In contrast, some other languages, like Perl, provide a dedicated "foreach" construct that automates this process. BOOST_FOREACH is just such a construct for C++. It iterates over sequences for us, freeing us from having to deal directly with iterators or write predicates.
  • Move: C++03과 C++11 컴파일러를 위한 이식성있는 이동 의미.
  • Parameter: Boost.Parameter 라이브러리 - 이름에 의해서 아규먼트들을 받아들이는 함수들을 작성한다.
  • Scope Exit: 종료범위에서 임의적인 코드 실행.
  • Typeof: operator 애뮬레이션에대한 typeof.

메모리

  • Pool: 메모리풀 관리.
  • Smart Ptr: 스마트 포인터(smart pointer) 클래스 템플릿.
  • Utility: Class noncopyable plus checked_delete(), checked_array_delete(), next(), prior() function templates, plus base-from-member idiom.

파싱

  • Spirit: LL parser framework represents parsers directly as EBNF grammars in inlined C++.

패턴과 숙어

  • Compressed Pair: 비어있는 멤버 최적화.
  • Flyweight: Design pattern to manage large quantities of highly redundant objects.
  • Signals: Managed signals & slots callback implementation.
  • Signals2: Managed signals & slots callback implementation (thread-safe version 2).
  • Utility: Class noncopyable plus checked_delete(), checked_array_delete(), next(), prior() function templates, plus base-from-member idiom.

프로그래밍 인터페이스들

  • Function: Function object wrappers for deferred calls or callbacks.
  • Parameter: Boost.Parameter Library - Write functions that accept arguments by name.

상태 머신들

  • Meta State Machine: A very high-performance library for expressive UML2 finite state machines.
  • Statechart: Boost.Statechart - Arbitrarily complex finite state machines can be implemented in easily readable and maintainable C++ code.

시스템

  • Chrono: 유용한 시간 유틸리티들.
  • Context: 문맥 스위칭 라이브러리.
  • Date Time: A set of date-time libraries based on generic programming concepts.
  • Filesystem: The Boost Filesystem Library provides portable facilities to query and manipulate paths, files, and directories.
  • System: Operating system support, including the diagnostics support that will be part of the C++0x standard library.
  • Thread: 이식성있는 C++ 멀티 쓰래딩.

갖가지 주제를 다루는

  • Conversion: 다형성과 Lexical Cast.
  • Lexical Cast: General literal text conversions, such as an int represented a string, or vice-versa, from Kevlin Henney.
  • Numeric Conversion: Optimized Policy-based Numeric Conversions.
  • Optional: 선택적 값들을 위한 구별되어지는 결합적인 랩퍼(wrapper).
  • Polygon: Booleans/clipping, resizing/offsetting and more for planar polygons with integral coordinates.
  • Program Options: The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.
  • Swap: 향상된 일반적인 교체(swap) 함수.
  • Timer: Event timer, progress timer, and progress display classes.
  • TR1: The TR1 library provides an implementation of the C++ Technical Report on Standard Library Extensions. This library does not itself implement the TR1 components, rather it's a thin wrapper that will include your standard library's TR1 implementation (if it has one), otherwise it will include the Boost Library equivalents, and import them into namespace std::tr1.
  • Tribool: 3-상태 불리언 타입라이브러리.
  • Utility: Class noncopyable plus checked_delete(), checked_array_delete(), next(), prior() function templates, plus base-from-member idiom.
  • Value Initialized: Wrapper for uniform-syntax value initialization, based on the original idea of David Abrahams.

깨진 컴파일러 회피방법

  • Compatibility: 표준 라이브러리를 따르지않는것을 위해 돕니다.
  • Config: Boost 라이브러리 개발자들이 컴파일러 특이방식에 적응하도록 돕는다; 라이브러리 유저를 위해서 고려되지않았다.

Revised $Date: 2012-08-29 18:37:51 -0400 (Wed, 29 Aug 2012) $

Distributed under the Boost Software License, Version 1.0.


번역 원문 : http://www.boost.org/doc/libs/1_51_0/?view=categorized

반응형
반응형

블로그 이미지

3DMP engines

3D그래픽스 물리 수학, 프로그래밍 GPU Shader 게임엔진 알고리즘 디자인패턴 matlab etc..





boost::str( boost::wformat(  L"%d %d %d %d   %d %d") % (Tm->tm_year+1900) %  (Tm->tm_mon+1)%  Tm->tm_mday   

                                                                                %  Tm->tm_hour %  Tm->tm_min %  Tm->tm_sec );



이와같은 구문에서  (Tm->tm_year+1900) ,  (Tm->tm_mon+1)에 괄호를 치지않으면 에러가난다





이하 첨부내용



http://bit1010.tistory.com/21






기본 사용법

CString
CString str;
str.Format("%s%03d", szSomeVar, nSomeVar);

타입 안정성을 중요시하는 C++ 에서는 안타깝게도 CString의 Format 계열 함수가 제공 되지 않는다.
그래서 버퍼를 잡아 C의 런타임함수인 sprintf 함수를 사용하는수 밖에 없다.
그러나 C++에서는 stream 객체가 있으므로 sprintf 보다 우아(?) 하게 사용 할수 있다.

#include <sstream>로 사용할수 있으며 input/output/ input&output 버전이 따로 존재한다.

stringstream  in & out
ostringstream out
istringstream in

유니 코드 버전은 위의 클래스 네임에 w만 앞쪽에 붙여 주면되고
stringstream 내의 함수 중에 str() 멤버 함수로 string 클래스의 객체와 같이 연동해서 쓸 수 있다.

STL
#include <string>
#include <sstream>
#include <iomanip>
 
using namespace std;
ostringstream strStream;
strStream << szSomeVar << setw(3) << setfill('0') << nSomeVar;
string str = strStream.str();

BOOST
#include <boost/format.hpp>
#include <string>
 
std::string someString;
someString = boost::str(boost::format("%s%03d") % szSomeVar % nSomeVar);

CString의 Format에 해당하는 STL 코드와 BOOST 코드




직접 구현하기

1. 코드프로젝트 
STL Format 

CString의 Format같은 기능을 함수로 구현해 놓은게 있다.
근데 VC6에선 제대로 컴파일이 안된다. 우선 string의 clear는 stlport에는 없다.

2. 권진호님
sprintf 와 string 과의 만남

3. codein.co.kr

#define _MAX_CHARS 8000

int Format(std::stringtxtconst TCHARszFormat,...)

{ 

    std::vector<TCHAR_buffer(_MAX_CHARS);

    va_list argList;

    va_start(argList,szFormat);

#ifdef _UNICODE

    int ret = _vsnwprintf(&_buffer[0],_MAX_CHARS,szFormat,argList);

#else

    int ret = _vsnprintf(&_buffer[0],_MAX_CHARS,szFormat,argList);

#endif

    va_end(argList);

    txt.assign(&_buffer[0],ret);

    return ret;

}


4. 본인은 CString의 FromatV함수로 간단히 구현했음.  차라리 CString을 사용하는게 낫지 않냐고 하시면..
내부 구현은 나중에 제대로 테스트후 적용해도 된다. ㅋ

UINT StrPrintf( string& rstr, const char *pFmt, ...  )
{  
    va_list args;
    va_start(args, pFmt);
    
    CString csMsg;
    csMsg.FormatV(pFmt, args);
    rstr = csMsg;
    
    va_end(args);
    return rstr.length();
}


반응형
반응형

제공: 한빛미디어 네트워크 기사

원문: http://www.onlamp.com/pub/a/onlamp/2006/04/06/boostregex.html
저자: Ryan Stephens, 한동훈 역

텍스트를 검색하고, 파싱하는 과정은 어수선하다. 처음에는 문자열을 토큰으로 나누고, 구조를 재빨리 해석하는 간단한 문제처럼 보였던 것이 루프, if/then 문장, 버그로 이뤄진 안개같은 상태로 변하다가 종국에는 반쯤 아니 완전히 정신나간 상태까지 진행된다. 처음에는 URL에서 호스트 이름을 가져오는 것처럼 쉬운 것이 나중에는 로그 파일을 분석하고, 날짜로 된 문자열을 검사하는 것과 같은 복잡한 작업으로 발전하고, 점점 다루기 어려운 것으로 변한다.

오래 전부터 정규식은 이런 진흙탕에서 프로그래머들을 구원했다. 작지만 암호같은 정규식은 원하는 거의 모든 형식을 표현할 수 있으며, 복잡한 파싱 코드를 작성하는 임무로부터 개발자들을 구원해준다. 정규식은 강력할 뿐만 아니라, 어떤 언어에서든지 사용할 수 있으며, Perl에서는 정규식이 코드의 대부분을 차지한다. 현대 프로그래밍 언어들은 정규식에 대해 표준화된 방법으로 지원한다. 여기에는 펄, 자바, C#, 루비, 파이썬등이 있다. 슬프게도, C++은 이 목록에 없다. 정규식에 대해 유일하게 표준화된 방법은 몇 안되는 POSIX C API 함수들 뿐이다. 그렇더라도 걱정하지는 마라. 아직 C++에는 희망이 있다.

존(John Maddock)이 한시적인 표준 라이브러리로 만든  Boost.Regex 라이브러리가 이 문제를 해결해준다. 더 좋은 소식은 C++ 표준화위원회(TR1)에서 C++의 다음 표준 라이브러리의 표준 라이브러리로 Boost.Regex를 포함시키기로 했다는 점이다. 이제부터 C++에서 정규식을 사용한다면 이 라이브러리를 사용하면 된다. 이 라이브러리는 모두의 것이다.

Boost.Regex를 사용하면 간단한 매칭(전화번호 검사 같은 것)에서 검색 및 치환 같은 모든 작업을 할 수 있다. 여기서는 Boost.Regex로 할 수 있는 다음 기본 기능들을 설명할 것이다.

  • 매칭
  • 간단한 파싱
  • 열거(Enumeration)
이 글을 모두 읽은 다음에는 Boost.Regex로 무엇을 할 것인가에 대한 좋은 아이디어만 생각하면 된다. Boost.Regex를 시작하기 전에, 정규식에 대한 간단한 소개부터 하겠다.

배경 및 정의

정규식 구문은 그 자체로 완전한 언어이며, 정규식을 이해하기 완전히 이해하려면 몇 줄의 설명으로는 어림도 없다. 따라서, 여기서는 간단한 내용만 소개할 것이며, 원한다면 정규식에 대해 보다 많은 것들을 설명하고 있는 페이지들을 참고 자료로 제공할 것이다.

정규식은 정규식 엔진이 해석하고, 대상 문자열에 적용하기 위한 문자들로 구성된 문자열이다. C++에서 정규식 엔진은 Boost.Regex에 해당한다. 엔진은 문자열에 대해 식을 평가하고, 해당 식이 대상 문자열의 일부분이라면 전체 문자열이 일치하는지, 아닌지를 확인한다. 정규식이 문자열의 일부분이라면, 불리언 표현 값이나 실제로 식을 만족하는 텍스트를 결과로 가져올 수 있다.

이 글에서는 일부러 매치(match)와 검색(search)을 특별한 의미로 사용한다. 주어진 문자열을 정규식이 매치한다고 얘기할 때는 전체 문자열이 식을 만족한다는 것을 의미한다. 예를 들어, 다음과 같은 정규식을 생각해보자.

역주: match와 search를 보통은 구별하지 않고, "검색한다"라고 얘기하지만, 저자가 match와 search를 구분하기 때문에 match는 매치로 옮겼다.

a+|b+

위 식은 a가 한 번 이상 나오거나 b가 한 번 이상 나오는 문자열을 매치한다. + 기호의 의미는 "문자가 한 번 또는 그 이상의 문자들을 매치하라"이다. 파이프 연산자(|)는 논리적으로 "또는"이라는 의미이다. 따라서, 다음과 같은 문자열은 위 정규식과 매치된다.

a
aaaaa
b
bbbb

그러나, 다음 문자열은 매치되지 않는다.

ab
aac
x

정규식 a+|b+이 의미하는 것은 의사코드로 "문자열이 a로만 되어 있고, a가 한 번 이상 나오는 경우 또는 문자열이 b로만 되어 있고, b가 한 번 이상 나오는 경우에 true를 반환하라"이다.

반대로, 문자열에서 정규식을 만족하는 하위 문자열을 찾는 경우에는 결과가 달라진다. 앞과 같은 정규식을 사용해서도 다음 문자열을 매치할 수 있다.

mxaaabfc
aabc
bbbbbxxxx

이는 대상 문자열의 하위문자열이 정규식을 만족하기 때문이다. 이 작은 차이 때문에 Boost.Regex에서 정규식을 테스트하는데 사용하는 클래스와 함수가 달라진다.
표1은 자주 쓰이는 정규식 토큰을 요약한 것이다. 테이블을 이용해서 몇 가지 예제를 제시하고, 그에 대해 살펴본 다음에 정규식이 갖는 표현력을 살펴보고, 예제 1의 코드를 복사해서 약간의 실험을 진행할 것이다. 일단, 정규식을 사용해서 텍스트를 검색하고, 파스하는 것이 쉽다는 것을 알게 되면, 이것을 사용할 수 밖에 없을 것이다.

기호      의미
c         특수문자가 아니라면 문자 c를 한 번 매치한다.
^         줄의 시작을 매치한다.
.         새 라인이 아닌 모든 문자를 매치한다
$         줄의 끝을 매치한다
|         식들의 논리 OR
()        그룹 표현
[]        문자 클래스 정의
*         0번 또는 그 이상의 매치
+         1번 또는 그 이상의 매치
?         0 또는 1번의 매치
{n}       표현식을 n번 매치
{n,}      표현식을 최소한 n번 매치
{n, m}    최소 n번에서 최대 m번까지 매치하는 식
\d        숫자
\D        숫자를 제외한 문자
\w        _을 포함한 알파벳 문자
\W        알파벳이 아닌 문자
\s        공백 문자(\t, \n, \r, \f)
\S        공백 문자가 아닌 것
\t        탭
\n        새 라인
\r        캐리지 리턴
\f        폼 피드(Form Feed)
\m        메타 문자(^, ., $, |, (), [], *, +, ?, \, or /)들을 이스케이프

나는 표준처럼 널리 쓰이는 펄 스타일의 정규 표현식을 사용하고 있다. POSIX는 표준화된 기본 문법과 확장 문법 두 가지를 정의하고 있으며, Boost.Regex는 이들 두 가지를 모두 제공하고 있지만, 여기서는 설명하지 않을 것이다. 표 1에서 나열한 것보다 더 많은 것들이 있지만, 정규표현식을 배우기에는 위의 것으로충분하다. 펄 스타일의 정규식에 대해 보다 자세한 참고자료를 원한다면 펄의 regex 문서를 찾아보면 되며, Boost.Regex에서만 사용하는 옵션에 대해서는 부스트 문서 페이지를 읽어보면 된다. 또한 인터넷에서 "regular expression syntax"로 검색하면 많은 결과들을 찾아볼 수 있다.

이제, 이걸로 무엇을 할까? 먼저, 9자리 숫자로 되어 있는 SSN - 한국의 주민번호에 해당 -을 생각해보자. SSN은 세번째와 다섯번째 숫자 다음을 하이픈(-)으로 구분한다. 즉, XXX-XX-XXXX와 같은 형식으로 사용하며, 다음과 같은 간단한 정규식으로 이를 검증할 수 있다.

\d{3}\-\d{2}\-\d{4}

\d는 숫자를 매치하며, \d 다음의 {3}는 숫자가 연속해서 세 번 나오는 것을 의미한다. 즉, \d\d\d 대신에 사용한다. \-는 하이픈(-)을 의미한다. 하이픈은 정규식에서 메타문자로 사용하기 때문에 앞에 \을 붙여서 하이픈(-)을 찾는다. 위 식은 지금 설명한 이 규칙을 사용한 것이다. 즉, 숫자 2개, 하이픈, 숫자 4개도 같은 규칙이다.

어떤 사람의 이름이 Johnson인지, Johnston인지 찾아보고 싶다면 다음과 같이 쓸 수 있다.

Johnst{0,1}on
Johnson|Johnston
Johns(on|ton)

첫번째 예에서 {0,1}은 여기에 올 수 있는 문자의 수를 의미한다. 여기서는 문자 t가 0번 또는 한 번 올 수 있음을 의미한다. 두번째는 논리 OR 연산자를 괄호없이 사용한 것이며, 세번째는 논리 OR 연산자를 괄호와 함께 사용한 것이다.

매칭

앞에서 설명한 것처럼, 전체 문자열이 식을 만족하면 문자열이 정규식과 일치(match)한다고 한다. 예1은 정규식을 사용하는 간단한 프로그램이지만, 정규식을 만족하는 문자열이 있는지를 알려줄 수 있다. 컴파일하고 실행하면서 정규식이 동작하는 것을 살펴보고, 정규식이 무엇인지 느껴보기 바란다.

#include <iostream>
#include <string>
#include <boost/regex.hpp>  // Boost.Regex lib

using namespace std;

int main( ) {

   std::string s, sre;
   boost::regex re;

   while(true)
   {
      cout << "Expression: ";
      cin >> sre;
      if (sre == "quit")
      {
         break;
      }
      cout << "String:     ";
      cin >> s;

      try
      {
         // Set up the regular expression for case-insensitivity
         re.assign(sre, boost::regex_constants::icase);
      }
      catch (boost::regex_error& e)
      {
         cout << sre << " is not a valid regular expression: \""
              << e.what() << "\"" << endl;
         continue;
      }
      if (boost::regex_match(s, re))
      {
         cout << re << " matches " << s << endl;
      }
   }
}

예제1. 간단한 정규식 테스트 프로그램

예제의 첫번째는 boost/regex.hpp를 포함하는 것이다. 이 헤더 파일은 Boost.Regex 라이브러리를 사용하는데 필요한 모든 것을 담고 있다. (부스트 라이브러리의 압축을 풀고, 빌드하는 것은 간단하며, 이에 대한 내용은 "부스트 시작하기"를 참고하기 바란다)

다음은 boost::regex 클래스다. 이 클래스는 정규식 그 자체를 포함하고 있다. 표준 문자열 클래스와 마찬가지로 narrow 문자와 wide 문자를 위한 클래스 템플릿((regex = basic_regex<char> and wregex = basic_regex<wchar_t>)을 지원한다.

regex 클래스에 정규식을 정의하기 전에는 흥미로운 것은 없다. 멤버 함수, 할당 연산자와 생성자를 해석하고, 정규식을 컴파일한다. 만약, 제대로 생성되지 않았다면 regex_error 예외를 일으킨다. assign에 대소문자 구분 무시를 의미하는 boost::regex_constants::icase를 사용했다.

마지막으로, regex_match가 모든 것을 처리한다. 여기에 사용된 매개변수는 대상 문자열과 regex 객체이다. 문자열이 표현식을 만족하면 true를 반환하고, 그렇지 않으면 false를 반환한다.

문자열을 정규식에 매칭하기 위해 Boost.Regex를 사용하는 가장 간단한 예이다. 이런 형식은 유효성 검사와 파싱에서 가장 일반적으로 사용된다.

유효성 검사

일반적으로, 사람들이 컴퓨터에 입력하는 모든 것은 의심해야하며, 검사하는 것이 필요하다. 물론, 문자 하나하나씩 비교하는 간단한 방법, if/then 구문을 이용해서 문자열의 유효성을 검사할 수 있다. 그렇지만 왜 그렇게 하는가? 보기에 지저분한 문자 하나하나씩 파싱하는 코드를 작성하느라 시간을 낭비하지말고, 코드를 간결하고, 작성하는 의도를 명확하게 할 수 있는 정규식을 사용하는 것이 낫다.

사용자가 일상적으로 잘못 입력하는 것 중에 좋은 예가 URL이다. 설정 파일이나 사용자가 입력한 위치에서 URL을 읽어들이는 응용프로그램이 있다고 해보자. 첫번째는 네트워크 라이브러리에 이 URL을 전달하기 전에 이 값이 올바른지 검증하는 것이다. 또는, 네트워크 라이브러리를 작성하고 있다면, URL을 해석하기 전에 URL의 형식이 맞는지부터 검사해야 한다. URL은 최소한 세 가지 구성요소 즉, 프로토콜, 호스트 이름, 경로로 되어 있다.

ftp://downloads.foo.com/apps/linux/patch.gz

FTP, HTTP, HTTPS 프로토콜을 사용할 수 있으며, URL을 검사하는 정규식은 다음과 같다.

(ftp|http|https):\/\/(\w+\.)*(\w*)\/([\w\d]+\/{0,1})+

호안의 첫번째 표현식, (ftp|http|https),은 프로토콜을 검사한다. 이 표현식은 URL에서 세 가지 프로토콜 중에 하나만 매치한다. 다음은 콜론(:)과 슬래시다. 슬래시는 제어 문자로 사용하기 때문에 여기서는 역슬래시(\)를 함께 사용해서 슬래시(/)를 표현한다. 다음은 (\w+W.)*(\w*)인데 foo.com 또는 foo와 같은 형태를 허용하는 것으로, 호스트 이름에서 문자와 숫자를 표시한다. 다음은 슬래시(/)이고, 그 다음은 ([\w\d]+\/{0,1})+이다. 이 식은 /downloads/w32/utils와 같은 형태의 경로 이름을 매치한다.

예제 1을 이용해서 다음과 같은 코드를 쉽게 작성할 수 있다.

try
{
   boost::regex re("(ftp|http|https):\/\/(\w+\.)*(\w*)\/([\w\d]+\/{0,1})+");
   if (!boost::regex_match(url, re))
   {
      throw "Your URL is not formatted correctly!";
   }
}
catch (boost::regex_error& e)
{
   cerr << "The regexp " << re << " is invalid!" << endl;
   throw(e);
}

regex_match는 문자열, char *, 이터레이터 범위, |' 표준 라이브러리 알고리즘을 처리하는 오버로딩 메서드를 갖고 있다.

앞의 코드 조각은 문법 검사를 수행한다. 문자열이 정규표현식을 만족하면, 행복할 것이다. 정규식의 길은 이걸로 끝이 아니다. 문자열의 구조를 검증하는 간단한 것 말고, 보다 복잡한 것들을 처리하는 것이 필요한 경우도 있다. 예를 들어, URL에서 호스트이름을 추출하는 것처럼, 문자열의 일부를 추출하고 그것을 처리하는 경우도 필요하다.

파싱

regex_match는 문자열이 표현식을 만족하는가의 여부만 확인하는 것 외에 문자열을 부분부분으로 나누는 것도 가능하다. match_result 객체에 결과를 저장하며, match_result는 결과를 조사하기 위해 반복(iterate)하는 시퀀스-표준 라이브러리 시퀀스를 의미-이다. 

예제 2는 예제1을 수정한 버전이다. 새 버전에서는 match_result<const char*>을 typedef한 cmatch를 포함하고 있다. 표준 라이브러리 문자열과 마찬가지로, Boost.Regex는 narrow 문자열과 wide 문자열을 모두 지원한다.

#include <iostream>
#include <string>
#include <boost/regex.hpp>

using namespace std;

int main( ) {

   std::string s, sre;
   boost::regex re;
   boost::cmatch matches;

   while(true)
   {
      cout << "Expression: ";
      cin >> sre;
      if (sre == "quit")
      {
         break;
      }

      cout << "String:     ";
      cin >> s;

      try
      {
         // Assignment and construction initialize the FSM used
         // for regexp parsing
         re = sre;
      }
      catch (boost::regex_error& e)
      {
         cout << sre << " is not a valid regular expression: \""
              << e.what() << "\"" << endl;
         continue;
      }
      // if (boost::regex_match(s.begin(), s.end(), re))
      if (boost::regex_match(s.c_str(), matches, re))
      {
         // matches[0] contains the original string.  matches[n]
         // contains a sub_match object for each matching
         // subexpression
         for (int i = 1; i < matches.size(); i++)
         {
            // sub_match::first and sub_match::second are iterators that
            // refer to the first and one past the last chars of the
            // matching subexpression
            string match(matches[i].first, matches[i].second);
            cout << "\tmatches[" << i << "] = " << match << endl;
         }
      }
      else
      {
         cout << "The regexp \"" << re << "\" does not match \"" << s << "\"" << endl;
      }
   }
}

예제2. 하위포현식을 사용한 문자열 파싱

예제2에서 matches는 sub_match 객체의 시퀀스다. sub_match 클래스는 멤버 first와 second를 갖고 있다. 이들은 원래 문자열에서 첫번째와 마지막에서 하나 지난(one-past-the-last)을 가리킨다. matches[0]는 원래 문자열 전체를 담고 있으며, sub_match 객체의 인덱스 [1..n]은 원래 표현식에서 상응하는 하위 표현식을 매치한 하위 문자열 n개를 가리킨다.

하위 표현식은 괄호 안에 포함된 원래 정규식의 일부분이다. 예를 들어, 다음 정규식은 하위 정규식을 세 개 갖고 있다.

(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})

이 정규식은 MM/DD/YY 또는 MM/DD/YYYY의 형태로 된 날짜들을 매치한다. 여기서는 값의 의미에 대해서는 검증하지 않기 때문에, 월에 해당하는 MM이 12보다 클 수도 있다. 어떻게 하면 각 부분을 잡아낼 수 있는가? 그림1이 아이디어를 설명해준다. 위 정규식을 문자열 11/5/2005에 사용하면 match_results 객체는 그림1과 같이 보게된다.

그림1 
그림1. regex_match의 결과

이 날짜를 해석하고 나면, matches에는 4개의 요소를 갖게 된다. 인덱스 0의 요소는 전체 문자열을 가리키며, matches에 있는 각 요소들은 원래 문자열에서 해당하는 하위 표현식을 만족하는 요소들을 가리킨다. 전체 문자열은 정규표현식을 매치하며, 각각의 하위 표현식은 match_results 시퀀스에서 인덱스 1-3으로 이용할 수 있다.

사용하고 있는 하위 표현식의 타입에 따라, match_results의 내용이 놀라운 것일 수도 있다. 위 URL 예제를 생각해보자. 정규 표현식은 하위 표현식 네 개를 갖고 있다. 굵은 글씨로 하위 표현식을 표시했다.

(ftp|http|https):\/\/(\w+\.)*(\w*)\/([\w\d]+\/{0,1})+

하위 표현식을 반복하는 것은(예를 들어, (\w+\.)*) 하위 표현식이 몇 번이든 매치할 수 있다는 것을 의미한다. 따라서, 매치된 결과는 차례대로 match_results에 저장된다. URL 정규 표현식을 사용해서 예제 2의 예제를 실행한 결과는 다음과 같이 된다.

정규식: (ftp|http|https):\/\/(\w+\.)*(\w*)\/([\w\d]+\/{0,1})+
문자열:     http://www.foo.com/bar
        matches[0] = http://www.foo.com/bar
        matches[1] = http
        matches[2] = foo.
        matches[3] = com
        matches[4] = bar

결과에서 "www."이 빠졌다는 것을 바로 눈치챘을 지도 모른다. 하위 표현식을 반복하는 것은 마지막으로매치된 하위 표현식만 저장하기 때문이다. 예를 들어, URL에서 전체 호스트 이름을 잡아내고 싶다면, 다음과 같이 굵은 괄호로 표시된 하위 표현식을 추가해야 한다.

(ftp|http|https):\/\/((\w+\.)*(\w*))\/([\w\d]+\/{0,1})+

이는 여러 개의 하위 표현식을 전체 호스트이름으로 묶는다. match_results 시퀀스에서 상응하는 sub_match 객체의 순서는 중첩된 하위 표현식의 트리가 깊이 우선, 왼쪽에서 오른쪽으로 탐색하는 순서로 결정된다. 수정된 정규식을 사용했을 때의 출력 결과는 다음과 같다.

표현식: (ftp|http|https):\/\/((\w+\.)*(\w*))\/([\w\d]+\/{0,1})+
문자열:     http://www.foo.com/bar
        matches[0] = http://www.foo.com/bar
        matches[1] = http
        matches[2] = www.foo.com
        matches[3] = foo.
        matches[4] = com
        matches[5] = bar

matches[2]에서 호스트 이름에 대한 하위 표현식의 매치 결과가 표시되는 것을 제외하면 이전과 동일하다.

이 기술을 사용해서 정규 표현식 구문을 연습해보면, 문자열을 검증하고, 파싱하는 작업 등에 Boost.Regex를 사용할 수 있을 것이다. 그러나, 이 예제들은 정규식의 강력한 능력의 일부분만 살펴본 것에 불과하다. 정규식에 익숙하지 않다면, 보다 많은 실험을 해보기 바란다. 아마, 정규식을 사용해서 여러분이 원하는 것을 얼마나 많이 할 수 있는지 안다면 놀랄 것이다.

검색

전체에서 하나의 문자열을 매칭하고 파싱하는 것은 원하는 문자열을 포함한 문자열을 찾아주는 검색의 문제를 해결해 주지 못한다. 

매칭과 마찬가지로, Boost.Regex는 정규식을 이용해서 문자열을 검색하는 두 가지 방법을 제공한다. 가장 간단한 경우로, 주어진 문자열과 정규 표현식의 매치 여부만 알고 싶은 경우다. 예제 3은 파일에서 각 라인을 읽어서, 정규표현식과 만족하는 문자열이 있으면, 해당 라인을 출력하는 grep을 간단하게 구현한 것이다.

#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <fstream>

using namespace std;
const int BUFSIZE = 10000;

int main(int argc, char** argv) {

   // Safety checks omitted...
   boost::regex re(argv[1]);
   string file(argv[2]);
   char buf[BUFSIZE];

   ifstream in(file.c_str());
   while (!in.eof())
   {
      in.getline(buf, BUFSIZE-1);
      if (boost::regex_search(buf, re))
      {
         cout << buf << endl;
      }
   }
}

예제3 간단한 grep

regex_match를 사용한 방법과 같이 regex_search를 사용할 수 있다.

주어진 패턴을 매치하는 모든 하위 문자열을 열거할 수도 있다. 예를 들어, 웹 크롤러를 작성하고 있고, 페이지 내에 사용된 모든 A 태그에 대해 반복하고 싶다고 해보자. A 태그를 잡아내기 위해 다음과 같은 정규 표현식을 사용할 수 있다.

<a\s+href="([\-:\w\d\.\/]+)">

grep 예제처럼 전체 라인을 반환하는 대신, 대상 URL만 필요하기 때문에 match_results에서 두번째 하위 표현식을 사용한다. 예제 4는 예제 3을 살짝 고친것이다.

#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <fstream>

using namespace std;
const int BUFSIZE = 10000;

int main(int argc, char** argv) {

   // Safety checks omitted...
   boost::regex re("<a\\s+href=\"([\\-:\\w\\d\\.\\/]+)\">");
   string file(argv[1]);
   char buf[BUFSIZE];
   boost::cmatch matches;
   string sbuf;
   string::const_iterator begin;
   ifstream in(file.c_str());

   while (!in.eof())
   {
      in.getline(buf, BUFSIZE-1);
      sbuf = buf;
      begin = sbuf.begin();

      while (boost::regex_search(begin, sbuf.end(), matches, re))
      {
         string url(matches[1].first, matches[1].second);
         cout << "URL: " << url << endl;
         // Update the beginning of the range to the character
         // following the match
         begin = matches[1].second;
      }
   }
}

예제4. A 태그를 사용하여 반복하기

예제 4에 작성된 정규표현식은 역슬래시를 많이 사용하고 있다. 특정 문자를 두 번 이스케이프하기 위해 필요하다. 한번은 컴파일러를 위해서, 다른 한 번은 정규 표현식 엔진을 위해서 이스케이프한 것이다.

예제 4는 예제3에서 사용한 것과 다른 regex_search 메서드를 사용한다. 이 버전은 검색된 문자들의 범위의 시작과 끝을 나타내는 양방향 이터레이터 인자를 두 개 사용한다. 매칭되는 하위 문자열에 접근하기 위해 matches[1].second가 나타내는 마지막 매치 다음에 문자를 시작지점을 나타내게 업데이트하는 한다.

이것이 일치한 패턴을 모두 나열하는 유일한 방법은 아니다. 이터레이터를 이용하는 쪽을 선호한다면 정규표현식 검색에서 결과에 대한 이터레이터 인퍼테이스를 제공하는 regex_token_iterator를 사용할 수 있다. 예제 4에서 URL 검색 결과에 대해 반복하는 부분을 다음과 같이 고칠 수 있다.

   // Read the HTML file into the string s...
   boost::sregex_token_iterator p(s.begin(), s.end(), re, 0);
   boost::sregex_token_iterator end;

   for (;p != end;count++, ++p)
   {
      string m(p->first, p->second);
      cout << m << endl;
   }

이게 전부는 아니다. 첫번째 토큰 이터레이터는 생성자의 마지막 인자로 0을 전달한다. 이는 정규 표현식을 만족하는 문자열에 대해 반복하라는 의미다. 이 값을 -1로 하면, 정규식을 만족하지 않는 하위 문자열에 대해 반복하라는 의미가 된다. 다시 말해서, 문자열을 토큰으로 나눈다. 각 토큰은 정규 표현식을 만족하는 것이 된다. 이를 사용하면 복잡한 구분자로 되어 있는 문자열을 원하는 토큰으로 나눌 수 있게 해준다. 예를 들어, 웹 페이지를 파싱하는 복잡한 경우에도 문서를 각 영역별로 나눌 수 있다.

확인할 것

여기서 설명한 것보다 Boost.Regex는 더 많은 것들을 제공한다. Boost.Regex 페이지의 문서는 많은 예제들을 제공하고 있으며, 위에서 설명한 문자열 검색외에 다음과 같은 것들도 할 수 있다.
  • 펄과 Sed 스타일의 형식 변환을 사용하는 검색과 치환
  • POSIX 기본 정규표현식과 확장 정규 표현식의 사용
  • 유니코드 문자열과 비표준 문자열 형식의 사용

정규표현식을 실험해보기 바란다. 같은 일을 하는 다양한 방법들이 존재하며, 원하는 것을 하는 정규식을 간결하게 만들 수 있는 방법이 없는지 확인해봐야 한다. 

결론

Boost.Regex는 C++에서 정규표현식 엔진을 구현하는 라이브러리다. 복잡하고, 번거로운 문자열 파싱 코드를 작성하는 대신, 이 라이브러리를 사용해서 문자열에 정규표현식을 사용해서 매치, 검색, 또는 검색 & 치환을 할 수 있다. Boost.Regex는 다음 버전의 C++ 표준 라이브러리로 승인되었으며, TR1의 구현(tr1 네임스페이스)에서 이것을 보게 될 것이다. 

Ryan Stephens은 애리조나 템페에 살고 있는 소프트웨어 엔지니어, 라이터, 학생이다. 그는 모든 언어로 프로그래밍하는 것, 특히 C++로 프로그래밍하는 것을 즐긴다.

 

 

출처 : http://network.hanbitbook.co.kr/view.php?bi_id=1218


블로깅한 포스트 : http://blog.naver.com/mydaylee/140035640151

반응형

+ Recent posts