问题描述
我已经编写了这段代码来实现上述问题的模板专业化,但是代码不正确,因为它是从我在顶部编写的模板函数返回的值,而没有检查我在下面编写的实际模板专业化函数寻找它 两个C风格的字符串中的较小者。所有测试用例无论对还是错都通过了,请帮助我解决此问题。 这是我的代码
代码:
#include "pch.h"
#include<iostream>
using namespace std;
template<typename T>
T smaller(T a,T b) {
if (a < b)
return a;
return b;
}
//template<typename T>
//T smaller(T a,T b,T c)
//{
// if (a < b && a < c)
// return a;
// else if (b < c && b < a)
// return b;
// else if (c < a && c < b)
// return c;
//
//}
template <>
const char* smaller<const char *>(const char *a,const char *b)
{
//int strcmp ( const char * str1,const char * str2 );
if (strcmp(a,b) == 0)
return "0";
else if (strcmp(a,b) > 0)
return b;
else if (strcmp(a,b) < 0)
return a;
}
//TEST(smaller,TestName) {
// EXPECT_EQ('B',smaller('a','B'));
// EXPECT_EQ(12,smaller(15,12));
// EXPECT_EQ(33.1,smaller(33.1,44.2));
// //EXPECT_TRUE(true);
//}
//TEST(smaller,TestName_2) {
// EXPECT_EQ('B','B','c'));
// EXPECT_EQ(12,12,13));
// EXPECT_EQ(33.1,44.2,44.5));
// //EXPECT_TRUE(true);
//}
TEST(smaller,TestName_3) {
string a = "ABC";
string b = "DEF";
EXPECT_EQ("ABC",smaller(a,b));
string c = "AB";
string d = "DE";
EXPECT_EQ("AB",smaller(c,d));
string e = "Ba";
string f = "Dd";
EXPECT_EQ("Ba",smaller(e,f));
}
解决方法
就像以前一样实现它
由于我不知道TEST
是什么,因此我在其他版本中进行了更改。
#include <cassert>
#include <cstring>
#include <iostream>
using namespace std;
template <typename T>
T smaller(T a,T b) {
if (a < b) return a;
return b;
}
template <>
const char *smaller<const char *>(const char *a,const char *b) {
int ans = strcmp(a,b);
if (ans == 0) {
return "0";
}
return ans > 0 ? b : a;
}
template <typename T>
void EXPECT_EQ(T ans,T give) {
assert(ans == give);
}
template <>
void EXPECT_EQ(const char *ans,const char *give) {
assert(!strcmp(ans,give));
}
int main() {
const char *a = "ABC";
const char *b = "DEF";
EXPECT_EQ("ABC",smaller(a,b));
const char *c = "AB";
const char *d = "DE";
EXPECT_EQ("AB",smaller(c,d));
const char *e = "Ba";
const char *f = "Dd";
EXPECT_EQ("Ba",smaller(e,f));
}
,
it works for me.
#include"pch.h"
#include <cassert>
#include <cstring>
#include <iostream>
using namespace std;
template <typename T>
T smaller(T a,T b) {
if (a < b) return a;
return b;
}
template <>
const char* smaller<const char*>(const char* a,const char* b) {
int ans = strcmp(a,b);
if (ans == 0) {
return "0";
}
return ans > 0 ? b : a;
}
//template <typename T>
//void EXPECT_EQ(T ans,T give) {
// assert(ans == give);
//}
//
//template <>
//void EXPECT_EQ(const char* ans,const char* give) {
// assert(!strcmp(ans,give));
//}
TEST(smaller,TestName_3) {
const char* a = "ABC";
const char* b = "DEF";
const char* aa = smaller(a,b);
EXPECT_EQ(a,aa);
const char* c = "AB";
const char* d = "DE";
const char* dd = smaller(c,d);
EXPECT_EQ(c,dd);
const char* e = "Ba";
const char* f = "Dd";
const char* ff = smaller(e,f);
EXPECT_EQ(e,ff);
}