C++ 在C+中键入转发+;11
以下情况:C++ 在C+中键入转发+;11,c++,c++11,return-type,decltype,trailing-return-type,C++,C++11,Return Type,Decltype,Trailing Return Type,以下情况: class CTest { public: CTest()=default; ~CTest()=default; auto SomeFunc_Helper(std::integral_constant<int, 8> param) -> uint64_t*; //param is in reality more or less a self-implemented std::integral_constant auto SomeFun
class CTest
{
public:
CTest()=default;
~CTest()=default;
auto SomeFunc_Helper(std::integral_constant<int, 8> param) -> uint64_t*; //param is in reality more or less a self-implemented std::integral_constant
auto SomeFunc() -> [how do I get the return type of SomeFunc_Helper?]
{
return SomeFunc_Helper(std::integral_constant<int, sizeof(uintptr_t)>{});
}
};
class-CTest
{
公众:
CTest()=默认值;
~CTest()=默认值;
auto SomeFunc_Helper(std::integral_constant param)->uint64_t*;//param实际上或多或少是一个自我实现的std::integral_常量
auto SomeFunc()->[如何获取SomeFunc\u助手的返回类型?]
{
返回SomeFunc_Helper(std::integral_常量{});
}
};
对于SomeFunc()
auto-SomeFunc()->decltype(&CTest::SomeFunc\u Helper(std::integral\u constant))
向我提供了无法解决的错误。
所以我的问题是如何从一个函数到另一个函数进行类型转发?
(不包括std::
名称空间的C++11以上的解决方案是受欢迎的)您可以尝试以下方法:
auto SomeFunc() -> decltype(SomeFunc_Helper(std::integral_constant<int, 8>()))
{
/* ... */
}
auto SomeFunc()->decltype(SomeFunc\u助手(std::integral\u constant())
{
/* ... */
}
在尾部返回类型中,
decltype
的参数可以是任何有效的表达式,在本例中,就是对函数体中实际执行的成员函数的准确调用。我认为您正在寻找,但是,在本例中,您只需将返回类型声明为decltype(auto)
(从C++14开始):
auto SomeFunc()->decltype(自动)
{
返回SomeFunc_Helper(std::integral_常量{});
}
这样,如果函数返回引用,例如,您也可以将引用完美地转发到
SomeFunction
。这是宏值得使用的情况之一
#define RETURNS(...) \
noexcept(noexcept(__VA_ARGS__)) \
-> decltype(__VA_ARGS__) \
{ return __VA_ARGS__; }
现在您可以:
auto SomeFunc()
RETURNS( SomeFunc_Helper(std::integral_constant<int, sizeof(uintptr_t)>{}) )
auto-SomeFunc()
返回(SomeFunc_Helper(std::integral_常量{}))
有人建议,
返回
等效功能将成为lambdas中的=>
或类似功能;我希望它将被推广。这是一个问题吗?它表达了某种程度的不确定性,我在发布我未测试的代码片段时总是感觉到:)无论如何,感谢@Ron的编辑。这最终会调用函数两次。我不确定这是否是提问者想要的。@AlexBdecltype
是一个未评估的问题context@AlexB您确定decltype
正在调用函数,并且您不仅仅看到return语句中调用的函数吗?传递std::integral_常量
参数有什么意义?此类型的所有对象都相同。auto SomeFunc()->uint64\u t*
@appleapple使代码更脆弱。现在,如果SomeFunc\u Helper
你也必须记得更改SomeFunc
。@NathanOliver是的,我知道。但谢谢你指出这一点。(只是看不到这里的必要性。(而且将来某一天SomeFunc可能需要返回与它的助手不同的类型。)@n.m.我更新了我的当前情况,希望它更清楚(我想要代码,它在32位系统上的位屏蔽与在64位系统上的不同)decltype(auto)
是一个C++14构造。此Q标记为C++11此解决方案将非常好,但正如@NathanOliver所写,我被允许使用高达C++11的功能(仅限不带std的核心语言:)@mbed_-dev所以你甚至不能使用std::result_of
?@mbed_-dev好的,我会把这个解决方案放在这里,也许它会对其他可能偶然发现这个问题的人有所帮助:-)非常感谢,不管怎样它都很有帮助
auto SomeFunc()
RETURNS( SomeFunc_Helper(std::integral_constant<int, sizeof(uintptr_t)>{}) )