在 C++11 中键入转发

Type forwarding in C++11

本文关键字:转发 C++11      更新时间:2023-10-16

以下情况:

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)>{});
}
};

SomeFunc()我尝试了类似的东西

auto SomeFunc() ->decltype(&CTest::SomeFunc_Helper(std::integral_constant<int, 8>))给了我无法解决std::integral_constant<int, 8>的错误。 所以我的问题是如何将从一个函数转发到另一个函数? (欢迎最多 C++11 的解决方案(不包括std::命名空间(

这是宏值得的情况之一。

#define RETURNS(...) 
noexcept(noexcept(__VA_ARGS__)) 
-> decltype(__VA_ARGS__) 
{ return __VA_ARGS__; }

现在,您可以:

auto SomeFunc()
RETURNS( SomeFunc_Helper(std::integral_constant<int, sizeof(uintptr_t)>{}) )

有人提议RETURNS等效功能将在 lambda 中变得=>或类似;我希望它能被概括。

你可以试试这个:

auto SomeFunc() -> decltype(SomeFunc_Helper(std::integral_constant<int, 8>()))  
{
/* ... */
}

尾随返回类型中要decltype的参数可以是任何有效的表达式,在本例中,是对函数体中实际执行的成员函数的确切调用。

我认为您正在寻找std::result_of,但是,在这种情况下,您应该只将返回类型声明为decltype(auto)(自 C++14 起(:

auto SomeFunc() -> decltype(auto)
{
return SomeFunc_Helper(std::integral_constant<int, 8>{});
}

这样,例如,如果函数返回引用,也可以完美地将引用转发给SomeFunction