将模板函数和重载作为函数参数传递
Passing template function and overload as function argument
简短版本:将函数指针作为参数传递给另一个函数时,是否可以混合使用模板函数和重载?
详细信息:我在模板函数中使用 std::search
,我想根据模板的类型控制使用哪个函数进行比较,例如对 char*
使用函数调用 strcmp
,对其他类型使用 operator==
。
到目前为止,我使用的是专门用于 char*
的模板仿函数,如下所示:
Comparator<T> comparator;
std::search(....., comparator);
也就是说,没有模板函数的模板特化这样的东西,因为它们只是简单的重载。那么,在这种情况下我是否坚持使用仿函数?
函数模板没有部分 特化。但我想你可能有一个更大的误解:"Is is possible to mix template functions and overloads when passing a function pointer ..." 重载决议发生在创建函数指针时。一旦创建了函数指针,就没有混合了。
也就是说,您似乎想要的是 政策。很难google当你不知道名字的时候,我知道。
具有完整模板专业化的解决方案:
#include <string.h>
#include <vector>
#include <algorithm>
// template function "MyComperator"
template<class T>
bool MyComperator( T a, T b ) {
return a < b;
}
// full template specialization for function "MyComperator" with type "char*"
template<>
bool MyComperator<char*>( char *a, char *b ) {
return strcmp( a, b ) < 0;
}
int main() {
std::vector<int> v1;
v1.push_back( 3 );
v1.push_back( 2 );
v1.push_back( 1 );
std::sort( v1.begin(), v1.end(), &MyComperator<int> );
std::vector<char*> v2;
v2.push_back( "C" );
v2.push_back( "B" );
v2.push_back( "A" );
std::sort( v2.begin(), v2.end(), &MyComperator<char*> );
return 0;
}
简短版本:将函数指针作为参数传递给另一个函数时,是否可以混合使用模板函数和重载?
详细信息:我在模板函数中使用 std::search
,我想根据模板的类型控制使用哪个函数进行比较,例如对 char*
使用函数调用 strcmp
,对其他类型使用 operator==
。
到目前为止,我使用的是专门用于 char*
的模板仿函数,如下所示:
Comparator<T> comparator;
std::search(....., comparator);
也就是说,没有模板函数的模板特化这样的东西,因为它们只是简单的重载。那么,在这种情况下我是否坚持使用仿函数?
函数模板没有部分 特化。但我想你可能有一个更大的误解:"Is is possible to mix template functions and overloads when passing a function pointer ..." 重载决议发生在创建函数指针时。一旦创建了函数指针,就没有混合了。
也就是说,您似乎想要的是 政策。很难google当你不知道名字的时候,我知道。
具有完整模板专业化的解决方案:
#include <string.h>
#include <vector>
#include <algorithm>
// template function "MyComperator"
template<class T>
bool MyComperator( T a, T b ) {
return a < b;
}
// full template specialization for function "MyComperator" with type "char*"
template<>
bool MyComperator<char*>( char *a, char *b ) {
return strcmp( a, b ) < 0;
}
int main() {
std::vector<int> v1;
v1.push_back( 3 );
v1.push_back( 2 );
v1.push_back( 1 );
std::sort( v1.begin(), v1.end(), &MyComperator<int> );
std::vector<char*> v2;
v2.push_back( "C" );
v2.push_back( "B" );
v2.push_back( "A" );
std::sort( v2.begin(), v2.end(), &MyComperator<char*> );
return 0;
}