Boost.Type_erasure:成员函数return _self
Boost.Type_erasure: member function return _self
我想在返回类型本身的成员函数上使用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();
}
相关文章:
- C++函数中的精确"return"矩
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 如何解决类成员函数中的"return a value"错误?
- 错误:调用 .. at return 语句时没有匹配函数
- 当你只使用 return 时,函数返回什么类型;在 c++ 中
- 编译器说这个函数必须返回一个值,但我已经有一个 return 语句
- 如果 return 语句在带括号的循环中,错误可能会到达非 void 函数的末尾,但不会显示在没有括号的循环的情况下
- return 语句,该语句调用在返回 void 的函数中返回 void 的函数
- 调用函数后返回 0 而不"return(0);"
- 为什么在"return 0"之后调用析构函数?
- 为什么"return 0"适用于在函数中返回指针,但不适用于参考?
- return语句中的C++constexpr函数
- 用return语句结束析构函数安全吗
- 控制达到非空隙函数的末端[-werror = return-type](只是一个简单的法官)
- 复制 ELISION:在 return 语句中使用三元表达式时未调用移动构造函数
- 当我在递归函数中调用 return 时,我的程序意外完成
- 返回 std::string 的函数在没有 return 语句的情况下崩溃,这与返回 int 而不返回语句的函数不同
- 为什么构造函数"return"这个指针?
- Boost.Type_erasure:成员函数return _self
- 我们必须在函数"return"末尾写什么?在 C++ 中