【问题标题】:Boost.Type_erasure: member function return _selfBoost.Type_erasure:成员函数返回_self
【发布时间】:2015-11-25 12:16:43
【问题描述】:

我想在返回类型本身的成员函数上使用 Boost.Type_erasure。以_self作为返回类型,就可以了。但是,当 返回类型 更改为 pair<_self, some_type> 时,会发生错误。下面的代码重现了这个问题。

#include <utility>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/member.hpp>

BOOST_TYPE_ERASURE_MEMBER((HasTest1), Test1, 0)
BOOST_TYPE_ERASURE_MEMBER((HasTest2), Test2, 0)

using boost::type_erasure::_self;
using std::pair;
using Type1 = boost::type_erasure::any<
    boost::mpl::vector<
    boost::type_erasure::copy_constructible<>,
    HasTest1<_self(), _self const>
    >,
    _self
>;
using Type2 = boost::type_erasure::any<
    boost::mpl::vector<
    boost::type_erasure::copy_constructible<>,
    HasTest2<pair<_self, int>(), _self const>
    >,
    _self
>;

int main() {
    struct test {
        test Test1() const { throw; }
        pair<test, int> Test2() const { throw; }
    };

    Type1{ test{} };// OK
    Type2{ test{} };// Error
    // Type2{ test{} }.Test2().first.Test2();// Expected to work
}

如何在不使用返回参数的情况下解决此问题?

示例错误消息:

main.cpp:6:1: error: no viable conversion from 'pair<test, [...]>' to 'pair<boost::type_erasure::_self, [...]>'

BOOST_TYPE_ERASURE_MEMBER((HasTest2), Test2, 0)

^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

【问题讨论】:

  • 您可能应该在 boost 邮件列表中询问,该库的作者通常会很快回答任何问题。如果您想要一些似乎有效的东西(通过反复试验),请查看this
  • @cv_and_he 谢谢。您的代码通过了编译。但是生成的对象不能调用 Test2()。
  • 请记住,我完全不知道自己在做什么,但 this 并没有失败(目前)。
  • @cv_and_he 没关系。我已将问题发布到 boost 邮件列表。但是您提供的代码仍然不起作用。 `终止调用没有活动异常'
  • 因为你的Test2 方法抛出...The next problem。我希望你能在邮件列表中得到真正的答案,因为它很有趣。

标签: c++ boost boost-type-erasure


【解决方案1】:

以下是Steven Watanabe的回应。

库只能处理顶层的占位符。没有办法自动处理一般情况,X&lt;_self&gt;。这与虚函数的协变返回类型基本相同,具有类似的限制。

要获得你想要的效果,你需要手动定义concept_interface

或者,我使用boost::any 来解决。

#include <utility>
#include <boost/any.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/member.hpp>

BOOST_TYPE_ERASURE_MEMBER((HasTest), Test, 0)

using Type = boost::type_erasure::any<
    boost::mpl::vector<
    boost::type_erasure::copy_constructible<>,
    HasTest<boost::any()>
    >
>;

int main() {
    struct TestType {
        auto Test() {
            return std::make_pair(0, Type{ *this });
        }
    };
    auto obj = Type{ TestType{} }.Test();
    boost::any_cast<std::pair<int, Type>&>(obj).second.Test();
}

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 2019-06-26
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多