c++ - 我需要实现模板功能的特化,该功能执行查找两个C风格字符串中较小的字符串的功能

标签 c++ unit-testing templates googletest template-specialization

我已经编写了此代码来实现上述问题的模板特化,但是代码不正确,因为它是从我在顶部编写的模板函数返回值,而没有检查我在下面编写的实际模板特化函数来查找
两个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/

相关文章:

c# - 如何将参数传递给使用 System.Action 作为输入参数的数据访问层?

c# - 如何模拟(使用 Moq)由 Newtonsoft.json 序列化的接口(interface)?

perl - 如何在perl中等待异步文件

javascript - 如何部分替换 Underscore.js 模板,或如何从模板创建模板

templates - Jinja 在包含或宏上保留缩进

c++ - 什么时候显式实例化模板是合适的?

c++ - 如何从远程计算机获取当前登录的用户名

c++ - 使用读取文件功能解码串行 GPS 时遇到问题

c++ - 超出范围错误,而请求的项目应该在绑定(bind)中

c++ - 为什么调用模板成员函数会出错?