这里有一个可能解决你问题的方法:不过我做了一些小小的改变。
-
圣
-我变了
Class A
到
Class Template
.
-
钕
-我添加了一个指向类型的指针
<T>
-
3.
研发部
-我加了一个
operator()()
到
A<T>
调用函数调用。
-
4.
th
-为了保持一致,我更改了函数指针的名称和其他类函数的名称。
-
th
-而不是使用
printf()
,我曾经
std::cout
.
以下是修改后的代码的外观:
阅读评论以了解其工作原理。
template<class T>
class A {
private:
// Need to save a pointer to the class to have a realitive object.
T* ptrT{ nullptr };
public:
// Assigns the pointer of the object to this's class's pointer member.
// Must pass by reference otherwise you will have undefined behavior.
explicit A( T& t ) : ptrT( &t ) {}
// Notice the Template Arguments class resolution operator...
void(T::*func)();
// The added operator()() to invoke the function call.
// This could of been any arbitrary member function;
// I just chose to use the operator() for demonstration.
void operator()() {
(ptrT->*func)();
}
};
// In class's A & B the only changes here are
// the names of the function and replacing printf() with cout
class B {
int ib{ 2 };
public:
void func() {
std::cout << ib << '\n';
}
};
class C {
int ic{ 6 };
public:
void func() {
std::cout << ic << '\n';
}
};
int main() {
try {
B b;
C c;
// Changes to A by using templates and passing the object
// above to A's explicit constructor
A<B> a1( b );
A<C> a2( c );
// Notice the syntax on how to assign the function pointer.
a1.func = &B::func;
a2.func = &C::func;
// using the operator() to invoke the function pointer.
a1();
a2();
} catch( std::runtime_error& e ) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
-输出-
2
6