在模板化成员函数中使用std :: function时出现编译错误,以下代码是一个简单示例:
#include <functional>
#include <memory>
using std::function;
using std::bind;
using std::shared_ptr;
class Test {
public:
template <typename T>
void setCallback(function<void (T, int)> cb);
};
template <typename T>
void Test::setCallback(function<void (T, int)> cb)
{
// do nothing
}
class TestA {
public:
void testa(int a, int b) { }
};
int main()
{
TestA testA;
Test test;
test.setCallback(bind(&TestA::testa, &testA, std::placeholders::_1, std::placeholders::_2));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
并带来以下编译错误:
testtemplate.cpp:在函数'int main()'中:
testtemplate.cpp:29:92:错误:没有匹配的函数调用"测试:: setCallback(STD :: _ Bind_helper)(INT,INT),种皮,常量性病:: _占位符<1>&,常量性病:: _占位符<2>&> ::类型)"
testtemplate.cpp:29:92:注意:候选者是:testtemplate.cpp:10:7:注意:模板void test :: setCallback(std …
代码如下:
#include <iostream>
using namespace std;
class A {
};
A rtByValue() {
return A();
}
void passByRef(A &aRef) {
// do nothing
}
int main() {
A aa;
rtByValue() = aa; // compile without errors
passByRef(rtByValue()); // compile with error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
g ++编译器给出以下错误:
d.cpp: In function ‘int main()’:
d.cpp:19:23: error: invalid initialization of non-const reference of type ‘A&’ from an rvalue of type ‘A’
d.cpp:12:6: error: in passing argument 1 of ‘void passByRef(A&)’
Run Code Online (Sandbox Code Playgroud)
它说我不能将rvalue作为非const引用的参数传递,但是我很困惑的是为什么我可以分配给这个rvalue,就像代码所示.
以下代码位于Heap.h文件中
template <typename T>
class Heap {
public:
Heap();
Heap(vector<T> &vec);
void insert(const T &value);
T extract();
T min();
void update(int index, const T &value);
/* for debug */
friend ostream &operator<< (ostream &os, const Heap<T> &heap);
#if 0
{
for (int i = 0; i < heap.vec_.size(); i++) {
os << heap.vec_[i] << " ";
}
return os;
}
#endif
private:
void minHeapify(int index);
int left(int index);
int right(int index);
int parent(int index);
void swap(int, int);
vector<T> vec_;
}; …Run Code Online (Sandbox Code Playgroud) 我正在努力学习命令式和函数式语言之间的差异.
而且,我想了解闭包以及如何实现垃圾收集器.所以我决定尝试为函数式语言实现解释器.
由于我不熟悉函数式语言,因此我很难设计它.是否有一些关于简单函数语言的语法和语义的资源?有关如何执行此操作的教程将非常有用.
functional-programming language-design language-implementation