我有下面的代码,我正在尝试编写一个泛型函数,它接受2个迭代器和一个对象并检查任何出现次数并返回出现次数.
低于我的简单课程
class person{
string name;
int age;
public:
person(string n, int a): name(n), age(a) {}
bool operator==(person &p);
};
bool person::operator==(person &p){
return (name == p.name && age == p.age);
}
Run Code Online (Sandbox Code Playgroud)
以下是通用功能
template<typename Iter, typename Obj>
int count_obj(Iter iter1, Iter iter2, Obj &obj){
int count = 0;
for (; iter1 != iter2; iter1++){
if((*iter1) == obj)
count += 1;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
我的主要:
int main(){
vector<person *> myp;
person a("ted", 21); person b("sun", 100); person c("ted", 21);
myp.push_back(&a);myp.push_back(&b);myp.push_back(&c); …Run Code Online (Sandbox Code Playgroud) 如何将模板化函数与STL提供的算法一起使用<algorithm>?例如,此代码无法编译,因为编译器无法推导出该predicate函数的模板参数:
#include <iostream>
#include <algorithm>
template< typename CharType >
bool predicate( const CharType& c )
{
return c == '0';
}
std::string
process_string( const std::string& str )
{
std::string result;
std::copy_if( str.begin( ),
str.end( ),
std::back_inserter( result ),
predicate );
return result;
}
int main()
{
std::cout << process_string("AK0NNDK0ASDAS0") << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我知道模板没有在C中定义.但在我的情况下,我有一个用C++编写的API,由C编写的应用程序使用.我希望在API中添加模板函数.该函数在abc.cpp中定义如下:
template<typename T> T function_name(T param1){
...
...
return val;
}
Run Code Online (Sandbox Code Playgroud)
abc.hpp中的声明如下:
template<typename T> T function_name(T);
Run Code Online (Sandbox Code Playgroud)
并且从xyz.c调用此函数:
int a ,b = 5;
a = function_name(b);
Run Code Online (Sandbox Code Playgroud)
但是,它在abc.cpp和abc.hpp中都显示以下错误:
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token
template<typename T>
Run Code Online (Sandbox Code Playgroud)
即使使用extern"C"也无济于事(导致错误:带C链接的模板).我怀疑的是,甚至可以用这种方式调用这个模板函数吗?如果是,那怎么能实现呢?谢谢.
我写了以下代码:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
template <class T> T Min(T a, T b)
{
cout<<"template function: ";
if(a<b)
return a;
return b;
}
char *Min(char *a, char *b)
{
cout<<"non-template function: ";
if(strcmp(a,b)==0)
return a;
return b;
}
int main()
{
char c[]="x",d[]="y";
cout<<Min('x','y')<<endl;
cout<<Min("x","y")<<endl;
cout<<Min(c,d)<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
template function: x
template function: y
non-template function: y
Run Code Online (Sandbox Code Playgroud)
第一个函数调用正常,它正在调用模板函数.但是,为什么第二个函数也调用模板函数,而它是一个字符串常量.不应该调用非模板函数???
另外为什么第二次函数调用的输出y不应该是x?使用字符串常量调用函数和char类型数组之间有什么区别,尽管两者都是字符串?