首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Boost.Type_erasure:成员函数返回_self

Boost.Type_erasure:成员函数返回_self
EN

Stack Overflow用户
提问于 2015-11-25 12:16:43
回答 1查看 201关注 0票数 0

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

代码语言:javascript
复制
#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
}

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

示例错误消息:

代码语言:javascript
复制
main.cpp:6:1: error: no viable conversion from 'pair<test, [...]>' to 'pair<boost::type_erasure::_self, [...]>'

BOOST_TYPE_ERASURE_MEMBER((HasTest2), Test2, 0)

^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EN

回答 1

Stack Overflow用户

发布于 2015-11-30 05:42:03

以下是渡边史蒂文的回应。

库只能在顶层处理占位符。没有办法处理一般情况,自动X<_self>。这与具有类似限制的虚拟函数的协变量返回类型本质上是一样的。

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

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

代码语言:javascript
复制
#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();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33916325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档