使用模板参数指定策略

时间:2020-04-27 15:53:54

标签: c++ templates

我知道我们还可以传递模板参数来选择应该执行哪个函数。我发现它们可以替代函数指针,因为函数指针具有运行时成本,而模板参数则没有。另外,模板参数可以内联,而函数指针则不能。

那么,这就是我写的以描述我对此的理解。我走近了,但在某处缺少一些细微的细节。

template<class T>
class String {
  public:
    T str;
    String() { std::cout << "Ctor called" << std::endl; }
};  

template<class T, class C>
int compare(const String<T> &str1,
            const String<T> &str2) {
  for (int i = 0; (i < str1.length()) && (i < str2.length()); ++i) {
    if (C::eq(str1[i], str2[i])) {
      return false;
    }   
  }   
  return true;
}   

template<class T>
class Cmp1 {
  static int eq(T a, T b) { std::cout << "Cmp1 called" << std::endl; return a==b; }
};  

template<class T>
class Cmp2 {
  static int eq(T a, T b) { std::cout << "Cmp2 called" << std::endl; return a!=b; }
};  

int main() {
  String<std::string> s;
  s.str = "Foo";
  String<std::string> t;
  t.str = "Foo";
  compare<String<std::string>, Cmp1<std::string> >(s, t);
  // compare(s, t);
}

代码详情:

我有一个String类,它带有一个参数并创建该类型的成员函数。 我有一个比较函数,它接受两个String&参数。比较函数传递给它。 Cmp1和Cmp2是两个比较功能。

compare<String<std::string>, Cmp1<std::string> >(s, t);

在这里无法编译。我尝试了其他方式打电话,但徒劳无功。

1 个答案:

答案 0 :(得分:1)

看起来您想要这样的东西:

#include <iostream>
#include <string>

template<class T>
class String {
  public:
    T str;
    String() { std::cout << "Ctor called" << std::endl; }
};  

template<class T, class C>
int compare(const String<T> &str1,
            const String<T> &str2) {
  for (int i = 0; (i < str1.str.length()) && (i < str2.str.length()); ++i) {
    if (C::eq(str1.str[i], str2.str[i])) {
      return false;
    }   
  }   
  return true;
}   

template<class T>
class Cmp1 {
public:
  static int eq(T a, T b) { std::cout << "Cmp1 called" << std::endl; return a==b; }
};  

template<class T>
class Cmp2 {
public:
  static int eq(T a, T b) { std::cout << "Cmp2 called" << std::endl; return a!=b; }
};  

int main() {
  String<std::string> s;
  s.str = "Foo";
  String<std::string> t;
  t.str = "Foo";
  compare<std::string, Cmp1<char> >(s, t);
  // compare(s, t);
}

code

说明: 您已经在String的定义中有了compare,您只需要发送T,在您的情况下就是std::string

相比之下,您正在尝试遍历整个std::string,因此,现在您的代码可以编译。

您在cmp上调用str[index],实际上是char,因此您需要使用char模板参数来调用cmp。