如何让一个带有方法的c++对象接受封闭类的参数
How to have a c++ object with a method that takes argument the enclosing class?
我正试图弄清楚c++中是否有任何已知的模式/习惯用法可以用于我在这里要做的事情。类A必须由一个具有函数的对象组成,该函数的参数也必须是类型A。以下代码不编译,因为typeid不能用于常量表达式中。有什么建议吗?
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
struct B {
int f(T& i) { cout << "Hellon"; }
};
class A {
B<typeid(A)> b;
};
int main()
{
A k;
}
您声明的需求根本不需要模板,只需要一个正向声明:
#include <iostream>
class A; // forward declare A
struct B {
int f(A &i); // declaration only, definition needs the complete type of A
};
class A {
B b;
};
int B::f(A &i) { std::cout << "Hellon"; } // define f()
int main()
{
A k;
}
您正在寻找B<A> b;
以下程序在g++4.4.3上编译时没有错误或警告。
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
struct B {
int f(T& i) { cout << "Hellon"; return 0; }
};
class A {
public:
B<A> b;
};
int main()
{
A k;
return k.b.f(k);
}
注意:如果您使用模板只是为了避免前向声明,那么我的解决方案是错误的。但是,我将把它留在这里,以防您出于其他正当原因使用模板。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象