【发布时间】:2020-06-07 15:10:00
【问题描述】:
我希望能够以 I 类的对象作为参数传递函数,其中 I 继承自 D,到 FD 构造函数::
class D {}; class I: public D {};
FD(std::function<void(D*)> f): _f(f) {}
void test(I*) { std::cout << "Success" << std::endl; }
FD fd(test); fd.call();
正如我一直在研究的那样,我应该实现type conversion,但我不知道一种干净的方法,也没有找到适用于我的案例的解决类型转换的答案。 完整代码如下:
#include <functional>
#include <iostream>
class D {}; class I: public D {};
class FD {
protected:
std::function<void(D*)> _f;
public:
explicit FD(std::function<void(D*)> f): _f(f) {}
void call() { _f(0); }
};
void test(I*) { std::cout << "Success" << std::endl; }
int main () {
FD fd(test); fd.call();
}
我明白了:
test.cpp: In function ‘int main()’:
test.cpp:17:13: error: no matching function for call to ‘FD::FD(void (&)(I*))’
FD fd(test); fd.call();
^
test.cpp:10:14: note: candidate: FD::FD(std::function<void(D*)>)
explicit FD(std::function<void(D*)> f): _f(f) {}
^~
test.cpp:10:14: note: no known conversion for argument 1 from ‘void(I*)’ to ‘std::function<void(D*)>’
我也尝试过使用 int 和 double:
#include <functional>
#include <iostream>
class FD {
protected:
std::function<void(double)> _f;
public:
explicit FD(std::function<void(double)> f): _f(f) {}
void call() { _f(0); }
};
void test(int v) { std::cout << "Success" << std::endl; }
int main () {
FD fd(test); fd.call();
}
有输出:
Success
【问题讨论】:
-
我对@987654327@ 和
double有效的情况感到惊讶,但这可能是因为int和double可以相互隐式转换。D*不能隐式转换为I*,只有相反的情况。如果你有class I {}; class D: public I {};,它会起作用。想象一下如果I有一个额外的成员。目前尚不清楚您要实现什么行为。 -
您好@FrançoisAndrieux,exaclty,如果FD 调用不在D 中的I 方法怎么办?如果期望一个 I 并给出一个 D,它肯定会崩溃。也许在预期 D 时给 I 是可以原谅的,以禁止不太确定性的崩溃?
标签: c++ functional-programming