Boost.Type_erasure:成员函数return _self

Boost.Type_erasure: member function return _self

本文关键字:函数 return 成员 self Type erasure Boost      更新时间:2023-10-16

我想在返回类型本身的成员函数上使用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)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

以下是Steven Watanabe的回复。

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

要获得所需效果,您需要手动定义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();
}