简体   繁体   中英

C++ making a console: binding a function

I am currently working on creating a console in c++. I have created a class to help link variables and functions in code to variables and functions in the console.

I currently have it set where if I have a variable in code, I can redefine it under the new class and it will be visible to the console. The variable in code still behaves the same as before.

Example:

float var = 1.0;

can be redefined as

ConsoleVar var("myVariable")<float> = 1.0;

var is the variable name in the code and myVariable is the name that you use to access it in the terminal

My question is:

How can I bind a function, or more specifically, detect the number and type of the arguments. I know that I can template the ConsoleVar class to a void * type to store a function but is there a way for me to auto detect the return type, number of arguments and type of arguments? I am planning on shipping this in a library so I am going for ease of use. If this is possible, I would really like to know (I'll even do assembly if needed) otherwise I have some ideas on how to implement it.

EDIT: So I think that I have a solution but I have a question... Is it possible to pass a variable number of arguments to a function. Not like varargs.

For instance: I recieve 3 args from the command line, now I execute the function

func(arg[1], arg[2], arg[3])

Is it possible to send a variable number of arguments?

This pattern will do the job.

#include <typeinfo>    

// Function with 0 parameters
template< typename Ret >
void examine_function( Ret (*func)() )
{
    std::cout << typeinfo(Ret).name() << std::endl;
}

// Function with 1 parameters
template< typename Ret, typename Param1 >
void examine_function( Ret (*func)(Param1) )
{
    std::cout << typeinfo(Ret).name() << std::endl;
    std::cout << typeinfo(Param1).name() << std::endl;
}

// Function with 2 parameters
template< typename Ret, typename Param1, typename Param2 >
void examine_function( Ret (*func)(Param1, Param2) )
{
    std::cout << typeinfo(Ret).name() << std::endl;
    std::cout << typeinfo(Param1).name() << std::endl;
    std::cout << typeinfo(Param2).name() << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM