gpt4 book ai didi

c++ - 如何让一个 c++ 对象的方法接受封闭类的参数?

转载 作者:太空宇宙 更新时间:2023-11-04 12:10:42 25 4
gpt4 key购买 nike

我想弄清楚 c++ 中是否有任何已知的模式/惯用法来实现我在这里尝试做的事情。 A 类必须由一个对象组成,该对象具有一个函数,该函数的参数也必须是 A 类型。以下代码无法编译,因为 typeid 不能用于常量表达式。有什么建议么?

#include <iostream>
#include <typeinfo>
using namespace std;

template <typename T>
struct B {
int f(T& i) { cout << "Hello\n"; }
};

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 << "Hello\n"; } // define f()

int main()
{
A k;
}

关于c++ - 如何让一个 c++ 对象的方法接受封闭类的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9982508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com