我想在返回类型本身的成员函数上使用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)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~发布于 2015-11-30 05:42:03
以下是渡边史蒂文的回应。
库只能在顶层处理占位符。没有办法处理一般情况,自动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();
}https://stackoverflow.com/questions/33916325
复制相似问题