我已经编写了此代码来实现上述问题的模板特化,但是代码不正确,因为它是从我在顶部编写的模板函数返回值,而没有检查我在下面编写的实际模板特化函数来查找
两个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', smaller('a', 'B','c'));
// EXPECT_EQ(12, smaller(15, 12,13));
// EXPECT_EQ(33.1, smaller(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));
}
关于c++ - 我需要实现模板功能的特化,该功能执行查找两个C风格字符串中较小的字符串的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63870340/