Last active
October 4, 2023 21:55
-
-
Save chudur-budur/bc2b51798e89ca8618153e198f488338 to your computer and use it in GitHub Desktop.
Test generic function pointer generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
##### Header file test.hpp ##### | |
*/ | |
#ifndef __TEST_HPP__ | |
#define __TEST_HPP__ | |
#include <complex> | |
#include <iostream> | |
// is_complex type checker | |
template <class T> | |
struct is_complex : public std::false_type | |
{ | |
}; | |
// is_complex type checker | |
template <class T> | |
struct is_complex<std::complex<T>> : public std::true_type | |
{ | |
}; | |
// actual function, just prints the value val | |
template <typename T> | |
void func(T val) | |
{ | |
if (is_complex<T>::value) | |
std::cout << "(" << val.real() << " + " | |
<< "j" << val.imag() << ")" << std::endl; | |
else | |
std::cout << val << std::endl; | |
} | |
// func() caller with an opaque parameter | |
template <typename T> | |
void func_opaque(void *val) | |
{ | |
T *v; | |
v = reinterpret_cast<T *>(val); | |
func(*v); | |
} | |
// function factory | |
template <typename fnT, typename T> | |
struct Factory | |
{ | |
fnT get() | |
{ | |
fnT f = func_opaque<T>; | |
return f; | |
} | |
}; | |
// function pointer to the func_opaque | |
typedef void (*fptr)(void *); | |
#endif // ########## End of header test.hpp | |
/** | |
########## test.cpp ########### | |
###### File for testing 1 ##### | |
*/ | |
#include "test.hpp" | |
#include <complex> | |
int main(void) | |
{ | |
fptr f = Factory<fptr, std::complex<double>>{}.get(); | |
std::complex<double> z = 1.0 + 0.5i; | |
f(&z); | |
return 0; | |
} | |
// compile: icpx -I. test.cpp | |
// run: ./a.out | |
// output: (1 + j0.5) | |
/** | |
########## test.cpp ########### | |
###### File for testing 2 ##### | |
*/ | |
#include "test.hpp" | |
#include <complex> | |
int main(void) | |
{ | |
fptr f1 = Factory<fptr, double>{}.get(); | |
double d = 7.0; | |
f1(&d); | |
return 0; | |
} | |
/** | |
In file included from test.cpp:1: | |
./test.hpp:21:32: error: member reference base type 'double' is not a structure or union | |
std::cout << "(" << val.real() << " + " | |
~~~^~~~~ | |
./test.hpp:32:5: note: in instantiation of function template specialization 'func<double>' requested here | |
func(*v); | |
^ | |
./test.hpp:40:17: note: in instantiation of function template specialization 'func_opaque<double>' requested here | |
fnT f = func_opaque<T>; | |
^ | |
test.cpp:10:39: note: in instantiation of member function 'Factory<void (*)(void *), double>::get' requested here | |
fptr f1 = Factory<fptr, double>{}.get(); | |
^ | |
1 error generated. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment