How to specify which namespace used by passing in function argument in C (arduino)
The objective is to select a namespace depending on the mode the program is running. Of course, the mode may change at runtime.
namespace A{
void init(){}
void run(){}
}
namespace B{
void init(){}
void run(){}
}
void function2(namespace X) { // this does not work.
X::init();
X::run();
}
void loop(){
// mode is defined elsewhere (actually a switch function is used)
if (mode == "A") {
function2(A);
} else if (mode == "B") {
function2(B);
}
}
CodePudding user response:
You cannot pass a namespace to a function (or method).
But you can pass a pointer to a function or method, like this:
#include <iostream>
namespace A {
void print() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
}
namespace B {
void print() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
}
void function(void (*print)()) {
print();
}
int main() {
function(A::print);
function(B::print);
}
Note: __PRETTY_FUNCTION__
is a GCC extension that expands to the pretty string name of the current function or method.
CodePudding user response:
you can use macro in C like this
#define function2(x) { using namespace x ; print();}
full source:
#include <iostream>
using namespace std;
namespace A{
void print(){
cout << "namespace A\n";
}
}
namespace B{
void print(){
cout << "namespace B\n";
}
}
#define function2(x) { using namespace x ; print();}
int main(){
function2(A);
function2(B);
}
tested at : https://godbolt.org/z/raq8Ks9cM
CodePudding user response:
It is not valid to have a function parameter specifying a namespace as you have in your example. From Storage class specifiers 7.1.1.2:
a variable declared as a function parameter has automatic storage duration by default.
But the concept of storage duration is applicable only to objects. And since namespaces are not objects(and neither are they types), they don't have storage duration and thus the syntax that you've in your program is incorrect. That is, we cannot pass a namespace as a function argument.
You can instead have a parameter as a pointer to a function as shown below.
Additionally, note that void main()
is not standard C . You should instead use int main()
as shown below.
#include <iostream>
namespace A{
void print(){
std::cout<<"A::print() called"<<std::endl;
}
void run(){
std::cout<<"A::run() called"<<std::endl;
}
}
namespace B{
void print(){
std::cout<<"B::print() called"<<std::endl;
}
void run(){
std::cout<<"B::run() called"<<std::endl;
}
}
//-------------vvvvvvvvvvvvvvv-------->function2 has a parameter named print that is a pointer to a function taking no parameters and with return type of void
void function2(void (*print)()) {
print();
}
int main(){//void main() changed to int main()
function2(A::print);
function2(A::run);
function2(B::print);
function2(B::run);
}