BOOST_FUSION_ADAPT_STRUCT を使って、構造体の関数越しにアクセスする2020年05月30日 12時28分12秒

BOOST_FUSION_ADAPT_STRUCT を使って、構造体の内部構造体にアクセスで、構造体内部に間接参照も出来ることが分かったので、更に実験。果して関数にアクセスすることは出来るのだろうか。

最初に実験したのはこれ。

#include <string>
#include <iostream>
#include <boost/fusion/algorithm.hpp>

#include <boost/fusion/include/adapt_struct.hpp>

struct person
{   
    std::string name_;
    int age_;

    erson( const std::string& name, int age )
        : name_( name )
        , age_( age )
    {
    }

    int age()
    {   
        return age_;
    }
};

BOOST_FUSION_ADAPT_STRUCT(
    person
    , ( std::string, name_ )
    , ( int, age() )
)

struct Print 
{   
    template< typename T >
    void operator()( const T& t ) const
    {   
        std::cout << t << std::endl;
    }
};

int main()
{   
    person p( "Boost User", 10 );
    boost::fusion::for_each( p, Print() );
}
コンパイルを試みる。
% c++ -I /usr/local/include boost_fusion_adapt_struct.cpp
boost_fusion_adapt_struct.cpp:24:1: error: non-const lvalue reference to type
      'int' cannot bind to a temporary of type 'int'
BOOST_FUSION_ADAPT_STRUCT(
^~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/fusion/adapted/struct/adapt_struct.hpp:75:13: note: 
      expanded from macro 'BOOST_FUSION_ADAPT_STRUCT'
            BOOST_FUSION_ADAPT_STRUCT_C)
無理なのかと思ったが、一時変数だと駄目だとある。参照を返すようにしたら大丈夫なのだろうか。

上記の age 関数を参照を返すように変えてみる。


int& age() { return age_; } コンパイルが無事に通った。
% c++ -I /usr/local/include boost_fusion_adapt_struct.cpp
% ./a.out 
Boost User
10
今回の使い方では読み出しのみなので、BOOST FUSION 以外の使い方は参照でも大丈夫なのだが、BOOST FUSION は他にも何かやっているのだろう。参照型だと、値を設定できるが setter 型の特殊な処理は無理だ。

前回