Как избежать boost :: phoenix при генерации с boost :: spirit :: karma

Я являюсь жертвой ошибки «LNK1179: неверный или поврежденный файл: дубликат COMDAT» и эти источники заставить меня поверить, что не используя phoenix Я мог бы избежать этой ошибки.

(Это продолжение к мой предыдущий вопрос.)
Я хочу заменить boost::phoenix с чем-то еще. Может быть boost::bind но я не понимаю, как я могу дать ему доступ к karma::_val,

Следующий код не скомпилируется на VC9 с

ошибка C2825: «F»: должен быть класс или пространство имен, после которого следует «::»

#include <boost/config/warning_disable.hpp>

#include <boost/foreach.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include <boost/bind.hpp>

#include <iostream>
#include <string>
#include <list>namespace karma = boost::spirit::karma;
namespace spirit = boost::spirit;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;class Item
{
public:
typedef std::vector<int> Values;

Item(const std::string  & i, const Values & v) : m_id(i), m_values(v) {}
std::string getId() const { return m_id; }
const Values & getValues() const { return m_values; }

private:
std::string m_id;
Values m_values;
};

class ItemList
{
public:
typedef std::map<std::string, Item> Items;

ItemList() {}
ItemList(const Items & s, const Items & o) : m_some(s), m_other(o) {}
const Items getSome() const { return m_some; }
const Items getOther() const { return m_other; }

private:
Items m_some;;
Items m_other;
};

template <typename Iterator>
struct list_generator : karma::grammar<Iterator, ItemList()>
{
list_generator(const ItemList & i)
: list_generator::base_type(start)
{
using karma::int_;
using karma::_1;
using karma::lit;
using karma::_val;

// using phoenix causes: fatal error LNK1179: invalid or corrupt file: duplicate COMDAT '?value@?$result_@U?$member_variable@$$A6E?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZP8Item@@AE?AV12@XZ@detail@phoenix@boost@@@?$is_mem_fun_pointer_select@$0A@@detail@boost@@2_NB'
// this is probably because the symbol names are too long.// Convert maps into lists containing only the values
const Items some  = boost::copy_range<Items>(i.getSome() | boost::adaptors::map_values);
const Items other = boost::copy_range<Items>(i.getOther() | boost::adaptors::map_values);

id =
lit("<id>")
<< karma::string
<< lit("</id>");

values =
lit("<values>")
<< (int_ % ';')
<< lit("</values>");

item =
lit("<item>")
//<< id[_1 = phoenix::bind(&Item::getId, _val)]
<< id[boost::bind(&Item::getId, &_val, _1)] // !! error C2825 !!
<< values[_1 = phoenix::bind(&Item::getValues, _val)]
<< lit("</item>");

start =
lit("<some>")     << (*item)[_1 = some] << lit("</some>")
<< lit("<other>")  << (*item)[_1 = other] << lit("</other>");
}

typedef std::vector<Item> Items;
karma::rule<Iterator, std::string()> id;
karma::rule<Iterator, Item::Values()> values;
karma::rule<Iterator, Item()> item;
karma::rule<Iterator, ItemList()> start;
};

int main()
{
const Item::Values values = boost::assign::list_of(1)(2)(3);
const Item a("a", values);
const Item b("b", values);

ItemList::Items some, other;
some.insert(std::make_pair(a.getId(), a));
other.insert(std::make_pair(b.getId(), b));
const ItemList items(some, ItemList::Items());

typedef std::back_insert_iterator<std::string> Iter;
typedef list_generator<Iter> Generator;

Generator grammar(items);

std::string generated;
Iter sink(generated);
if (!karma::generate(sink, grammar))
{
std::cout << "Generating failed\n";
}
else
{
std::cout << "Generated: " << generated << "\n";
}

return 0;
}

Полная ошибка заключается в следующем:

error C2825: 'F': must be a class or namespace when followed by '::'
1>        c:\path\to\boost\boost/bind/bind_template.hpp(15) : see reference to class template instantiation 'boost::_bi::result_traits<R,F>' being compiled
1>        with
1>        [
1>            R=boost::_bi::unspecified,
1>            F=std::basic_string<char,std::char_traits<char>,std::allocator<char>> (__thiscall Item::* )(void) const
1>        ]
1>        .\spiritTest.cpp(85) : see reference to class template instantiation 'boost::_bi::bind_t<R,F,L>' being compiled
1>        with
1>        [
1>            R=boost::_bi::unspecified,
1>            F=std::string (__thiscall Item::* )(void) const,
1>            L=boost::_bi::list2<boost::_bi::value<boost::phoenix::actor<boost::phoenix::composite<boost::phoenix::reference_eval,boost::fusion::vector<boost::spirit::attribute<0>,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_,boost::fusion::void_>>>>,boost::_bi::value<boost::spirit::_1_type>>
1>        ]
1>        .\spiritTest.cpp(57) : while compiling class template member function 'list_generator<Iterator>::list_generator(const ItemList &)'
1>        with
1>        [
1>            Iterator=Iter
1>        ]
1>        .\spiritTest.cpp(116) : see reference to class template instantiation 'list_generator<Iterator>' being compiled
1>        with
1>        [
1>            Iterator=Iter
1>        ]

1

Решение

Вы не можете использовать boost::bind выражения как актер феникс.

Что касается длинных искаженных имен, я не удивлюсь, если использование других TMP-тяжелых библиотек внесет значительный вклад (например, Boost Range, у которого есть собственный лес экземпляров шаблонов, возвращающих представления из адаптеров и т. Д.).

Вы могли бы попробовать

  1. Адаптация Item структурировать последовательность слияния: (с или без attr_cast<>)

    • В том же духе, вы могли бы сделать item правило сам потреблять последовательность слияния непосредственно
  2. Чтобы «подготовить» актера для использования в семантическом действии, либо

    • используя объект полиморфной функции (a.k.a. отложенный вызываемый объект)
    • или используя бесплатную функцию
  3. Выпекать на заказ phoenix::function<> актеры для getId() а также getValues() (для полноты)

Далее я продемонстрирую все подходы, завершив их полным примером программы, которая включает все эти параметры и скомпилированной с помощью gcc 4.5.3 для Windows (Cygwin).


1. Адаптация Item структурировать последовательность слияния:

BOOST_FUSION_ADAPT_ADT(Item,
(std::string,         std::string,         obj.getId(),     (void)val)
(Item::Values const&, Item::Values const&, obj.getValues(), (void)val)
)

// the rule becomes simply
item =
lit("<item>")
<< id      // yay for fusion magic!
<< values
<< lit("</item>");

Это может на самом деле сделать вещи одинаково плохими внутренне — это трудно понять с моей точки зрения. Если это произойдет, вы можете попытаться выделить фазу, в которой атрибуты используются в выражениях разбора, и место, где fusion adapter proxies оцениваются:

item =
lit("<item>")
<< karma::attr_cast<boost::fusion::vector<std::string, Item::Values> > // cast up front
(
id     // directly
<< values //
)
<< lit("</item>");
  • В том же духе, вы могли бы сделать item правило сам потреблять последовательность слияния прямо вместо Item пример. Это конечно удалить всю сложность bind / proxy из выражений парсера, но требуется больше работы, чтобы подключить остальные генераторы.

2. «предварительно приготовить» актера для использования в семантическом действии, либо

  • используя объект полиморфной функции (a.k.a. отложенный вызываемый объект):

    struct deferredGetId
    {
    template<typename,typename,typename> struct result { typedef void type; };
    
    template<typename Attr, typename Ctx, typename Bool>
    void operator()(Attr& attribute, Ctx const& context, Bool& flag) const
    {
    attribute = boost::fusion::at_c<0>(context.attributes).getId();
    flag = true;
    }
    };
    
  • или используя бесплатную функцию. Это тогда требует жесткого кодирования аргумента шаблона для контекста. Полезное объяснение роли Духовного контекста в правилах кармы можно найти здесь: повысить дух семантических параметров действия

    // non-template free function
    void hardcodedGetId(std::string& attribute,
    boost::spirit::context<boost::fusion::cons<const Item&, boost::fusion::nil>, boost::fusion::vector0<> > const& context,
    bool& flag)
    {
    attribute = boost::fusion::at_c<0>(context.attributes).getId();
    flag = true;
    }
    
  • Обратите внимание, что есть также BOOST_PHOENIX_ADAPT_FUNCTION что позволяет использовать шаблон функции напрямую, но все, что на самом деле делает, — это оборачивает шаблон функции в новый тип объекта Polymorphic Function, как описано выше, так что это ничего не даст вам.

Теперь вы можете использовать их в своих правилах:

 item =
lit("<item>")
<< id [_1 = phoenix::bind(&Item::getId, _val)] // works fine on GCC :)
<< id [deferredGetId()] // approach #1 (a)
<< id [hardcodedGetId]  // approach #1 (b)
<< values[_1 = phoenix::bind(&Item::getValues, _val)]
<< lit("</item>");

3. Использование phoenix::function обернуть отложенные вызовы

Наконец есть возможность использовать phoenix::function обернуть отложенные вызовы непосредственно как (унарный) актер. Я не уверен, что это на самом деле поможет вам, если нет какого-то подчистка происходит, что я не знаю.
Но конечный результат довольно элегантен, что само по себе является хорошим поводом упомянуть его, хотя бы для полноты:

struct GetId
{
template<typename> struct result { typedef std::string type; };
template<typename Item>
std::string operator()(Item const& item) const { return item.getId(); }
};

struct GetValues
{
template<typename> struct result { typedef Item::Values type; };
template<typename Item>
typename Item::Values const& operator()(Item const& item) const { return item.getValues(); }
};

boost::phoenix::function<GetId>     phx_getId;
boost::phoenix::function<GetValues> phx_getValues;

Это, вы можете использовать просто так:

item =
lit("<item>")
<< id[_1 = phx_getId(_val)]
<< values[_1 = phx_getValues(_val)]
<< lit("</item>");

Полный пример кода

#include <boost/config/warning_disable.hpp>

#include <boost/foreach.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include <boost/bind.hpp>

#include <iostream>
#include <string>
#include <list>

#include <boost/fusion/adapted.hpp>

namespace karma = boost::spirit::karma;
namespace spirit = boost::spirit;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;

class Item
{
public:
typedef std::vector<int> Values;

Item(const std::string  & i, const Values & v) : m_id(i), m_values(v) {}
std::string getId() const { return m_id; }
const Values & getValues() const { return m_values; }

private:
std::string m_id;
Values m_values;
};

class ItemList
{
public:
typedef std::map<std::string, Item> Items;

ItemList() {}
ItemList(const Items & s, const Items & o) : m_some(s), m_other(o) {}
const Items getSome() const { return m_some; }
const Items getOther() const { return m_other; }

private:
Items m_some;;
Items m_other;
};

/////////////////////////////////////////////
// 1. Adapting the `Item` struct

BOOST_FUSION_ADAPT_ADT(Item,
(std::string,         std::string,         obj.getId(),     (void)val)
(Item::Values const&, Item::Values const&, obj.getValues(), (void)val)
)

/////////////////////////////////////////////
// 2. Precooking Actors

struct deferredGetId
{
template<typename,typename,typename> struct result { typedef void type; };

template<typename Attr, typename Ctx, typename Bool>
void operator()(Attr& attribute, Ctx const& context, Bool& flag) const
{
attribute = boost::fusion::at_c<0>(context.attributes).getId();
flag = true;
}
};

// non-template free function
void hardcodedGetId(std::string& attribute,
boost::spirit::context<boost::fusion::cons<const Item&, boost::fusion::nil>, boost::fusion::vector0<> > const& context,
bool& flag)
{
attribute = boost::fusion::at_c<0>(context.attributes).getId();
flag = true;
}

/////////////////////////////////////////////
// 3. phoenix::function

struct GetId
{
template<typename> struct result { typedef std::string type; };
template<typename Item>
std::string operator()(Item const& item) const { return item.getId(); }
};

struct GetValues
{
template<typename> struct result { typedef Item::Values type; };
template<typename Item>
typename Item::Values const& operator()(Item const& item) const { return item.getValues(); }
};

boost::phoenix::function<GetId>     phx_getId;
boost::phoenix::function<GetValues> phx_getValues;

template <typename Iterator>
struct list_generator : karma::grammar<Iterator, ItemList()>
{
list_generator(const ItemList & i)
: list_generator::base_type(start)
{
using karma::int_;
using karma::_1;
using karma::lit;
using karma::_val;

// using phoenix causes: fatal error LNK1179: invalid or corrupt file:
// duplicate COMDAT
// '?value@?$result_@U?$member_variable@$$A6E?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZP8Item@@AE?AV12@XZ@detail@phoenix@boost@@@?$is_mem_fun_pointer_select@$0A@@detail@boost@@2_NB'
// this is probably because the symbol names are too long.

// Convert maps into lists containing only the values
const Items some  = boost::copy_range<Items>(i.getSome() | boost::adaptors::map_values);
const Items other = boost::copy_range<Items>(i.getOther() | boost::adaptors::map_values);

id =
lit("<id>")
<< karma::string
<< lit("</id>");

values =
lit("<values>")
<< (int_ % ';')
<< lit("</values>");

item =
lit("<item>")
//
<< id[_1 = phoenix::bind(&Item::getId, _val)] // works fine on GCC :)
<< id [deferredGetId()]     // approach #2 (a)
<< id [hardcodedGetId]      // approach #2 (b)
<< id [_1= phx_getId(_val)] // approach #3
//
<< values[_1 = phoenix::bind(&Item::getValues, _val)]
<< values[_1 = phx_getValues(_val)]
<< lit("</item>");

item =
lit("<item>")
<< id     // approach #1: using BOOST_FUSION_ADAPT_ADT
<< values // approach #1: using BOOST_FUSION_ADAPT_ADT
<< lit("</item>");

// approach #2 _with_ attr_cast:
item =
lit("<item>")
<< karma::attr_cast<boost::fusion::vector<std::string, Item::Values> >
(
id     // 'native' fusion sequence access
<< values // 'native' fusion sequence access
)
<< lit("</item>");

start =
lit("<some>")     << (*item)[_1 = some] << lit("</some>")
<< lit("<other>") << (*item)[_1 = other] << lit("</other>");
}

typedef std::vector<Item> Items;
karma::rule<Iterator, std::string()> id;
karma::rule<Iterator, Item::Values()> values;
karma::rule<Iterator, Item()> item;
karma::rule<Iterator, ItemList()> start;
};

int main()
{
const Item::Values values = boost::assign::list_of(1)(2)(3);
const Item a("a", values);
const Item b("b", values);

ItemList::Items some, other;
some.insert(std::make_pair(a.getId(), a));
other.insert(std::make_pair(b.getId(), b));
const ItemList items(some, ItemList::Items());

typedef std::back_insert_iterator<std::string> Iter;
typedef list_generator<Iter> Generator;

Generator grammar(items);

std::string generated;
Iter sink(generated);
if (!karma::generate(sink, grammar))
{
std::cout << "Generating failed\n";
}
else
{
std::cout << "Generated: " << generated << "\n";
}

return 0;
}
5

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector