我有api功能f_api(std::function<void(int)> func),现在我有我的流程类
class Func {
public:
void operator()(int i) {
// do some work
}
int operator()(int i, int j) {
// do some other work
}
};
Run Code Online (Sandbox Code Playgroud)
我想用Func ff(int i)传递给f_api来完成工作; 所以我使用std :: bind
Func f;
std::function<void(int)> func = std::bind(&Func::operator(), &f, std::placeholders::_1);
f_api(func);
Run Code Online (Sandbox Code Playgroud)
但问题是,如何指出Func::operator()()我想要绑定哪个?我可以通过它的名称给出一个成员函数,但是当这个成员函数有多个不同的签名重新加载函数时,如何处理它呢?请问std :: bind能找到最适合调用的函数吗?C++太复杂了......
最小可验证的案例:
#include <iostream>
#include <functional>
using namespace std;
class Func {
public:
void operator()(int i) {
// do some work
cout << "i is: " << i << …Run Code Online (Sandbox Code Playgroud) 为什么我要为接口由指针分配的类型断言结果赋值,而当我对由结构对象分配的接口执行此操作时,会出现“无法分配”错误?
这是我的代码:
package main
import (
"fmt"
)
type Person interface {
SayHi()
}
type Student struct {
id int
name string
}
func (s Student) SayHi() {
fmt.Println("hi, i am", s.name, " my id is:", s.id)
}
func main() {
p1 := Person(&Student{id: 123, name: "William"})
p1.SayHi() // ok
p1.(*Student).SayHi() // ok here
p1.(*Student).id = 456 // ok here
p2 := Person(Student{id: 123, name: "William"})
p2.SayHi() //ok
p2.(Student).SayHi() // ok here
p2.(Student).id = 456 // error here and why? …Run Code Online (Sandbox Code Playgroud) 假设我们有一个函数sum需要两个num并返回它的总和:
def sum(a, b):
return a + b
Run Code Online (Sandbox Code Playgroud)
我们想用map来计算某个可迭代容器的总和:
map(sum, [(1, 2), (3, 4)])
Run Code Online (Sandbox Code Playgroud)
它会引发异常:
TypeError: sum() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
这里发生的是在参数(1,2)和(3,4)上调用sum,这给了我们一个错误.我们能做到这一点:
sum(*(1,2))会正确返回.这是我的问题:我们怎样才能使用地图将这个元组优雅地传递给它?这是一个解决方案,但不如我想要的那样优雅:
map(lambda x: sum(*x), [(1, 2), (3, 4)])
Run Code Online (Sandbox Code Playgroud) 我已经阅读了“Effective Modern C++”的 item31 和http://en.cppreference.com/w/cpp/language/lambda 的网页,想知道我是否可以通过它的确定类型而不是包装类型来定义 lambda std::function 或关键字 ofauto以及如何实现。
例如,对于类型int:
auto x_1 = 5; // type deduction
int x_2 = 5; // defined by definite type
// both x_1, x_2 are int variables of value 5
Run Code Online (Sandbox Code Playgroud)
现在,当问题出现在 lambda 上时:
auto f_1_0 = []()->int{return 5;};
std::function<int(void)> f_1_1 = []()->int{return 5;};
SomeType f_2 = []()->int{return 5;}; // what's the SomeType here?
Run Code Online (Sandbox Code Playgroud) 当我编写python时,我喜欢这样做:
d = {"apple": "red", "book":["history", "art", "science"]}
print json.JSONEncoder().encode(d)
Run Code Online (Sandbox Code Playgroud)
然后我得到JSON字符串
'{"apple":"red","book":["history","art","science"]}'
Run Code Online (Sandbox Code Playgroud)
但是当我想在Golang中这样做时,事情变得更加复杂,我必须首先定义结构:
type Gadget struct {
Apple string
Book []string
}
g := Gadget{Apple: "red", Book: []string{"history", "art", "science"}}
bytes, _ := json.Marshal(g)
fmt.Println(string(bytes))
Run Code Online (Sandbox Code Playgroud)
是否有一些golang lib可以帮助我操作像python这样的JSON字符串?我可能有很多JSON,它们有不同的结构来处理.定义它们都是一项繁琐的工作.我甚至认为没有lib,因为golang中没有索引操作符重载机制.
你们说什么?