Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++11 包装函数C+的返回类型+;11_C++11 - Fatal编程技术网

C++11 包装函数C+的返回类型+;11

C++11 包装函数C+的返回类型+;11,c++11,C++11,我重新安排了一个关于std::forward with模板的示例 我使用了一个包装器函数,如果我将它声明为void函数,那么一切都很好。它按预期工作 #include<iostream> using namespace std; template <typename T, typename U> auto summation(T const &a, U const& b) -> decltype(T{}, U{}) { cout

我重新安排了一个关于std::forward with模板的示例

我使用了一个包装器函数,如果我将它声明为void函数,那么一切都很好。它按预期工作

 #include<iostream>
 using namespace std;

 template <typename T, typename U>
 auto summation(T const &a,  U const& b) -> decltype(T{}, U{})  {
    cout << "call by lvalue" << endl;
      return a+b;
 }

 template <typename T, typename U>
 auto summation(T&& a, U && b) -> decltype(T{},U{}) {
    cout << "call by rvalue" << endl;
      return a+b;
 }  

 template<typename T,typename U> void func(T&& a, U && b)  { 
  summation(forward<T>(a), forward<U>(b));

 }


 int main() {

 int x = 10;
 double y = 20;

 func(x,y);
 func(10,20);

 }
#包括
使用名称空间std;
模板
自动求和(T常量&a,U常量&b)->decltype(T{},U{}){

cout
decltype
表示在其参数中给出的表达式的类型

decltype(T {}, U {})
将是表达式的类型
T{},U{}
。这里有逗号运算符,因此表达式的类型是逗号后面表达式的类型,也就是
U{}
,因此
decltype(T{},U{})
给出类型
U
(更准确地说,
U&
,我猜,因为它是右值)

你想要的是

decltype(T{} + U{})


(感谢Jonathan Wakely,请参阅注释)。

您确定
decltype(T{},U{})
是一个有用的构造吗?“decline(type)是C++o1扩展…”?拒绝?您的第二个
求和
重载不只是针对右值,它还将针对非常量左值调用。您不需要两个重载,请阅读为什么不直接使用
模板自动函数(t&&a,U&&b)->decltype(求和(向前(a),向前(b)){返回求和(向前(a),向前(b));}
?它应该能正确处理所有情况。是的,JohnB这很好用,Jonathan建议的decltype(a+b)也能用,但只有当我使用auto res=summation((forward(a),forward(b))。如果我使用return summation(forward(a),forward(b)),它就无法编译,声明“对double类型的no const左值引用不能绑定decltype的临时类型(int()+double());
decltype(a+b)
会更好,晚指定的返回类型的要点是它们可以引用函数参数。谢谢Jonathan,它使用您的建议编译。但是decltype(T{}+U{})没有,使用a+b有什么区别?
 template<typename T,typename U> U func(T&& a, U && b)   {
 auto res =  summation(forward<T>(a), forward<U>(b));
 return res;

 } 
 static_cast<T&&>(t) 
decltype(T {}, U {})
decltype(T{} + U{})
decltype(a+b)