I would like to have pointer to template function which has 2 parameters of type T
.
template <typename T>
typedef bool( * f )( T, T );
template <typename T>
bool mniejsze (T pierwszy , T drugi){
if( pierwszy < drugi)
return true;
return false;
}
template <typename T>
bool wieksze (T pierwszy, T drugi){
if( pierwszy > drugi )
return true;
return false;
}
But I get:
error: template declaration of 'typedef'|
EDIT: Then I would like to pass that pointer: Is it the right way?
template <typename T>
T minmax(T a[], int n,bool &f){
return f(a[0],a[1]);
}
In C++11 you can use aliases:
template<typename T>
using f = bool( *)( T, T );
usage:
f<int> f1 = wieksze;
f1( 3, 4);
In C++03 there is a workoround:
template<typename T>
struct f {
typedef bool( *type)( T, T );
};
usage:
f<int>::type f1 = mniejsze<int>;
f<int>::type f2 = mniejsze<int>;
f1( 3, 4);
template<typename T>
T minmax(T a[], int n, typename f<T>::type fp ){
if ( fp( a[0], a[1])) return 1;
return -1;
}
int main() {
// your code goes here
f<int>::type f1 = wieksze<int>;
bool b = f1( 3, 4);
int a[] = { 3, 4};
std::cout << minmax<int>( a, 0, f1);
return 0;
}
In C++11 you can do:
template<class T>
using f = bool(*)(T, T);
And use:
f<int> fp = wieksze;
How about the following?
template <typename T>
struct FNPTR {
typedef bool (*f)( T, T );
};
Put a dummy wrapper of a struct, and use FNPTR::f later? For example,
FNPTR::f = mniejsze<char>;
This should work!
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.