본문 바로가기
코딩취미/C,C++

[c,c++] 함수 이름을 동적으로 생성해서 사용하기, 함수 이름 변경 호출 방법 10가지

by 브링블링 2024. 1. 6.
728x90

함수 이름을 동적으로 생성해서 사용하기

함수 이름을 동적으로 생성하는 방법은 프로그래밍 언어와 컴파일러에 따라 다를 수 있습니다. 다음은 C 및 C++에서의 몇 가지 방법을 포함하여 10가지 방법을 나열합니다.

함수이름 동적 생성방법 10가지

1. 매크로와 ## 연산자 사용:

#define FUNCTION_NAME(prefix, suffix) prefix##_function_##suffix

void FUNCTION_NAME(print, int)(int value) {
    printf("Value: %d\n", value);
}

// 사용
FUNCTION_NAME(print, int)(42);

 

2. 함수 포인터 사용:

#include <stdio.h>

typedef void (*FunctionPointer)(int);

void generateAndCallFunction(const char* prefix, const char* suffix, int value) {
    FunctionPointer func = (FunctionPointer)(&printf);
    printf("Value: %d\n", value);
}

// 사용
generateAndCallFunction("print", "int", 42);

 

3. 함수 포인터 배열 사용:

#include <stdio.h>

typedef void (*FunctionPointer)(int);

void print_int(int value) {
    printf("Value: %d\n", value);
}

// 함수 포인터 배열
FunctionPointer functionArray[] = { print_int };

// 사용
functionArray[0](42);

 

4. 함수 객체와 함수 호출 연산자 사용 (C++에서):

#include <iostream>

class FunctionObject {
public:
    void operator()(int value) const {
        std::cout << "Value: " << value << std::endl;
    }
};

// 사용
FunctionObject functionObj;
functionObj(42);

 

5. 템플릿 함수 사용 (C++에서):

#include <iostream>

template <typename Prefix, typename Suffix>
void generateAndCallFunction(int value) {
    std::cout << "Value: " << value << std::endl;
}

// 사용
generateAndCallFunction<int, int>(42);
728x90

6. 문자열 연결 연산자 + 사용:

#include <iostream>
#include <string>

void generateAndCallFunction(const std::string& prefix, const std::string& suffix, int value) {
    std::string functionName = prefix + "_function_" + suffix;
    std::cout << "Value: " << value << std::endl;
}

// 사용
generateAndCallFunction("print", "int", 42);

 

7. std::function 사용 (C++11 이상):

#include <iostream>
#include <functional>

void print_int(int value) {
    std::cout << "Value: " << value << std::endl;
}

// 사용
std::function<void(int)> functionObj = print_int;
functionObj(42);

 

8. 문자열 매크로 사용 (C++11 이상):

#include <iostream>

#define FUNCTION_NAME(prefix, suffix) prefix##_function_##suffix

void FUNCTION_NAME(print, int)(int value) {
    std::cout << "Value: " << value << std::endl;
}

// 사용
FUNCTION_NAME(print, int)(42);

 

9. 변수 이름으로 함수 호출 (C++17 이상):

#include <iostream>

void print_int(int value) {
    std::cout << "Value: " << value << std::endl;
}

// 사용
auto function = print_int;
function(42);

 

10. std::map을 활용한 함수 이름과 함수 포인터 매핑 (C++):

#include <iostream>
#include <map>
#include <functional>

void print_int(int value) {
    std::cout << "Value: " << value << std::endl;
}

// 사용
std::map<std::string, std::function<void(int)>> functionMap = {
    {"print_int", print_int}
};

functionMap["print_int"](42);
728x90