问题
I am trying to use weak function in a class in C++. Below is what I wrote:
#include <stdio.h>
#include <iostream>
class A {
public:
void func(int argc, char *argv[]) __attribute__((weak));
};
// optional definition:
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
if (a1.func){
a1.func(argc, argv);
} else {
printf("func() not available\n");
}
return 0;
}
But this gives below compilation error:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:21:16: error: cannot convert ‘A::func’ from type ‘void (A::)(int, char**)’ to type ‘bool’
if (a1.func){
^
If I move the func() outside a class and use gcc instead of g++, it compiles fine and works as expected. Can someone please tell what's the problem. Basically I want to achieve calling some class functions only if they are available (an optional feature) without using Compiler flags in cpp file.
回答1:
C++ has a standard mechanism for this. No need for linker tricks.
class Base {
public:
virtual void func(int argc, char *argv[])
{
printf("func() not available\n");
}
};
class A : public Base {
public:
#if 0
void func(int argc, char *argv[]) override;
#endif
};
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
a1.func(argc, argv);
}
来源:https://stackoverflow.com/questions/61266803/how-to-use-weak-function-in-c