使用内联实例化时谓词继承编译错误

Ric*_*ard 1 c++ templates stl g++

我正在使用测试框架(tut)并注意到了很多可重复性,所以我开始抽象出我需要的谓词函数.下面是一个简化的例子.

它有效,但我希望我能在一条线上完成它.问题是当我尝试实例化内联的派生谓词类时,它无法编译.有什么想法吗?

#include <string>
#include <functional>
#include <iostream>


using namespace std;


template <class T>
struct TestPredicate : public binary_function<T,T,bool>
{
  virtual bool operator() (const T& expected, const T& data) const = 0;
};

template <class T>
struct IsEqual : public TestPredicate<T>
{
  virtual bool operator() (const T& expected, const T& data) const
  {
    cout << "IsEqual: " << expected << ", " << data << endl;
    return data == expected;
  }
};

template <class T>
struct IsNotEqual : public TestPredicate<T>
{
  virtual bool operator() (const T& expected, const T& data) const 
  {
    cout << "IsNotEqual: " << expected << ", " << data << endl;
    return data != expected;
  }
};

struct Tester
{
  template <class T>
  void test( const T& data, const T& expected, TestPredicate<T>& value_condition ) 
  {
    if ( value_condition( expected, data ) ) 
    {
      cout << "PASSED" << endl;
    }
    else 
    {
      cout << "FAILED" << endl;
    }
  }
};


int main() 
{
  Tester test;

  string data("hello");
  string expected("hello");

  // this doesn't compile with an inline instantiation of IsEqual
  //test.test( data, expected, IsEqual<string>() );   // compilation error (see below)

  // this works with an explicit instantiation of IsEqual
  IsEqual<string> pred;
  test.test( data, expected, pred );

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译输出:

test2.cpp: In function ‘int main()’:
test2.cpp:61:48: error: no matching function for call to ‘Tester::test(std::string&, std::string&, IsEqual<std::basic_string<char> >)’
test2.cpp:61:48: note: candidate is:
test2.cpp:40:8: note: void Tester::test(const T&, const T&, TestPredicate<T>&) [with T = std::basic_string<char>]
test2.cpp:40:8: note:   no known conversion for argument 3 from ‘IsEqual<std::basic_string<char> >’ to ‘TestPredicate<std::basic_string<char> >&’
Run Code Online (Sandbox Code Playgroud)

使用g ++ 4.6.3

Bo *_*son 5

除了其他答案之外,您并不需要使用虚函数的运行时多态性.您可以让测试人员使用另一个模板参数:

template<class T, class Pred>
void test( const T& data, const T& expected, Pred value_condition ) 
Run Code Online (Sandbox Code Playgroud)