어떤 클래스의 non static 멤버의 포인터를 가져오고 싶다면 아래와 같이 코딩을 해서 해결할 수 있습니다. thread를 생성하는 방법으로 설명하겠습니다.

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

#define	IS_STATIC	1	

class foo
{
public:
#if IS_STATIC
	static void bar()
#else
	void bar()
#endif
	{
		for (int i = 0; i < 5; ++i) {
			std::cout << "Thread 3 executing\n";
			//++n;
			std::this_thread::sleep_for(std::chrono::milliseconds(10));
		}
	}
};

int main()
{
	int n = 0;
	foo f;
#if IS_STATIC	
	std::thread t5(foo::bar); // t5 runs foo::bar() on object f
#else
	std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f
#endif // 0
	t5.join();

}
std::thread t5(&foo::bar, &f);

인스턴스 f의 bar 함수를 수행하는 스레드를 생성하기 위한 코드입니다. 이를 위해 f의 포인터를 넘기고, member pointer인 &foo::bar까지 같이 넘깁니다.

그러면 static function이 만들어지고 이를 t5가 수행하게 됩니다.

위처럼 코딩하면 non static 멤버의 포인터를 이용할 수 있습니다. getter를 굳이 만들지 않고서도요. 하지만 이는 thread를 생성할때 문법적으로 맞춰줘야 하는 부분이므로 굳이 다른 상황에서 이용할 필요는 없을것 같습니다.

** 만일 static 메서드라면 아래와 같이 이용할 수 있습니다. static이기 때문에 인스턴스는 param에서 제외되도 됩니다.

std::thread t5(foo::bar);

 

'C++ > 코딩' 카테고리의 다른 글

c파일와 cpp파일 mix 빌드  (0) 2022.09.03

최근 회사일을 진행하면 cpp에서 c 함수를 불러와야하는 일이 있습니다. 확실하게 해두기 위해 아래와 같이 정리합니다.

 

cpp 코드

#include <iostream>

extern "C" {
void test_c_func();
}

int main(void)
{
    test_c_func();

    printf("i'm a c++ file\n");
    return 0;
}

/**
extern "C" void f(int); // one way
extern "C" {            // another way
int g(double);
double h();
};
void code(int i, double d)
{
    f(i);
    int ii = g(d);
    double dd = h();
    // ...
}
*/

c

#include <stdio.h>

void test_c_func();

void test_c_func()
{
    printf("i'm a c file\n");
}

CMakefiles.txt

add_executable(
    test
    test.cpp
    test.c
)

결과

[100%] Built target test
yeopgi@DESKTOP-NHP2NBA:~/coding/c++_coding/mixing_c_cpp(master)$ ./test 
i'm a c file
i'm a c++ file
yeopgi@DESKTOP-NHP2NBA:~/coding/c++_coding/mixing_c_cpp(master)$ ls -al

만일 extern "C" {} 처리를 하지않으면 빌드 에러가 발생합니다.

yeopgi@DESKTOP-NHP2NBA:~/coding/c++_coding/mixing_c_cpp(master)$ make
Scanning dependencies of target test
[ 33%] Building CXX object CMakeFiles/test.dir/test.cpp.o
[ 66%] Linking CXX executable test
/usr/bin/ld: CMakeFiles/test.dir/test.cpp.o: in function `main':
test.cpp:(.text+0x9): undefined reference to `test_c_func()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.dir/build.make:99: test] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/test.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
yeopgi@DESKTOP-NHP2NBA:~/coding/c++_coding/mixing_c_cpp(master)$

'C++ > 코딩' 카테고리의 다른 글

c++ member pointer  (0) 2022.11.02

+ Recent posts