functionobject 연구의 5

교묘한 검출 자리 표시자


boost는 에서_1부터 _까지9개의 자리 표시자, 9개의 변수입니다.이러한 변수는 본질적으로 하나의 템플릿 클래스의 실례화 대상이다. 특수한 점은 이 템플릿 클래스arg<>는 1-9의 정수만 템플릿 매개 변수로 수신한다는 것이다.다음은 템플릿 파라미터를 검출하는 방법과 템플릿 파라미터가 요구에 부합되지 않을 때 어떻게 컴파일하고 오류를 보고하는지 상세하게 소개한다.
구체적인 정의는 다음과 같다.
boost::arg<1> _1;
boost::arg<2> _2;
boost::arg<3> _3;
boost::arg<4> _4;
boost::arg<5> _5;
boost::arg<6> _6;
boost::arg<7> _7;
boost::arg<8> _8;
boost::arg<9> _9;

template< int I > struct arg
{
    arg()
    {
    }

    template< class T > arg( T const & /* t */ )
    {
        // static assert I == is_placeholder<T>::value
        typedef char T_must_be_placeholder[ I == is_placeholder<T>::value? 1: -1 ];
    }
};

template< int I > bool operator==( arg<I> const &, arg<I> const & )
{
    return true;
}

template< int I > struct is_placeholder< arg<I> >
{
    enum _vt { value = I };
};

template< int I > struct is_placeholder< arg<I> (*) () >
{
    enum _vt { value = I };
};

template< class T > struct is_placeholder
{
    enum _vt { value = 0 };
};

설명:
1. arg<> 템플릿 클래스에는 두 개의 구조 함수가 있습니다. 기본 구조 함수는 실행할 때 호출됩니다.템플릿 구조 함수는 컴파일할 때 호출됩니다. 이것이야말로 1-9 정수 파라미터를 진정으로 받아들인 함수입니다.그런데 왜classT가arg<1>타입인지 아직 이유를 모르겠어요.
2.is_placeholder가 여기서 분석을 했어요.http://blog.csdn.net/sheismylife/article/details/8268644
3. 수조의 초기화 길이가 0보다 작으면 안 된다는 것을 이용하여 번역기 검사를 한다.
typedef char T_must_be_placeholder[ I == is_placeholder<T>::value? 1: -1 ];
이 말은 우선char수조를 사용했는데 수조의 이름은 T가 반드시placeholder이어야 한다는 뜻이다.placeholder는 바로arg<1>에서arg<9>까지의 9개의 전역 변수입니다. 또는_1부터 _까지구.
하면, 만약, 만약...1 또는_9 매개 변수로 boost::arg 대상을 구성하면 컴파일이 통과됩니다.왜냐하면 is_placeholder<_1>::value의 값은 틀림없이 1이고 I와 비교하면 I도 원래 1이기 때문에 I==is_placeholder:value의 결과는true이고 최종 그룹의 길이는 1입니다.
하지만 전달하는 것은_1부터 _까지9 이외의 매개 변수, 수조 길이는 -1.컴파일러가 오류를 보고합니다.
boost::arg<1> arg1(_1);// , _1 
string str;
boost::arg<1> arg2(str);// , str 

/usr/src/boost_1_47_0/boost/bind/arg.hpp: In constructor ‘boost::arg::arg(const T&) [with T = std::basic_string, int I = 1]’:In file included from/usr/src/boost_1_47_0/boost/bind/bind.hpp:29:0, from/usr/src/boost_1_47_0/boost/bind.hpp:22, from main.cpp:12:main.cpp:59:27: instantiated from here/usr/src/boost_1_47_0/boost/bind/arg.hpp:37:22: error: size of array is negative
이것도 ==,?:조작부호는 모두 컴파일하는 동안 값을 구할 수 있다

좋은 웹페이지 즐겨찾기