据我所知,右值引用不能绑定到左值。例如,
\n\nvoid func(Foo &&f) {}\nint main() {\n Foo f;\n func(f);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n编译器抱怨:\n 错误:无法将 \xe2\x80\x98Foo&&\xe2\x80\x99 类型的右值引用绑定到 \xe2\x80\x98Foo 类型的左值
\n\n但是,为什么右值引用类型的模板参数可以绑定到左值?\ne.g.
\n\ntemplate <typename T> void funcTemp(T &&arg) {}\nint main() {\n Foo f;\n funcTemp(f);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n编译器不会报告该错误。\n为什么?
\n为了显示工作git存储库的分支名称,我对PS1变量进行了以下设置.
function parse_git_branch {
local branch
# Direct stderr to null device in case it's not in a git repo.
branch=$(git symbolic-ref HEAD 2> /dev/null);
# Zero length if it's not in a git repo.
if [ ! -z $branch ];
then
# remove the matched part of pattern.
echo "(${branch#refs/heads/})";
fi
}
PS1="\n\w$BASH_LIGHT_GREEN \$(parse_git_branch)$BASH_WHITE\n$ ";
Run Code Online (Sandbox Code Playgroud)
问题:为什么我必须在美元符号命令之前加上反斜杠?如果我删除反斜杠,它不会正确显示分支名称.
任何人都可以解释为什么调用a.Abs()有效吗?在我看来,'a'是*Vertex类型的变量,但*Vertex类型不实现Abs方法.
package main
import (
"fmt"
"math"
)
type Abser interface {
Abs() float64
}
func main() {
var a Abser
v := Vertex{3, 4}
a = &v // a *Vertex implements Abser
// In the following line, v is a *Vertex (not Vertex)
// and does NOT implement Abser, but why does this calling work?
fmt.Println(a.Abs())
}
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
Run Code Online (Sandbox Code Playgroud)