编译器不考虑基类

时间:2016-05-08 16:54:58

标签: c++ templates

我尝试创建一个框架,允许开发人员在不同的抽象层次上编写处理程序。因此,我尝试编写一个基本处理程序,它具有较少抽象的接口,并使用更抽象的接口调用派生的处理程序,并使用例如默认操作。这样:

template<typename Derived>
struct base {
    template<typename A>
    int operator () (int x, A& a) {
        return (*reinterpret_cast<Derived*>(this))(x) + a;
    }
};

派生的处理程序应该只需要实现简单的接口:

struct derived: public base<derived> {
    int operator () (int x) { return x; }
};

但是当我像这样使用它时:

int main(int, char**) {
    derived d;
    std::cout << d(1, 2) << std::endl;
}

我从g++ -c -Wall -Werror test2.cpp得到了以下输出(gcc版本是5.3.1):

test2.cpp: In function 'int main(int, char**)':
test2.cpp:18:24: error: no match for call to '(derived) (int, int)'
     std::cout << d(1, 2) << std::endl;
                        ^
test2.cpp:12:9: note: candidate: int derived::operator()(int)
     int operator () (int x) { return x; }
         ^
test2.cpp:12:9: note:   candidate expects 1 argument, 2 provided

我也尝试过使用clang vresion 3.8.0(clang++ -c -Wall -Werror test2.cpp)并得到类似的结果:

test2.cpp:18:18: error: no matching function for call to object of type 'derived'
    std::cout << d(1, 2) << std::endl;
                 ^
test2.cpp:12:9: note: candidate function not viable: requires single argument 'x', but 2 arguments were provided
    int operator () (int x) { return x; }
        ^
1 error generated.

不考虑基类中的调用操作符模板。我也尝试使用不同的方法名称,因为运算符可能在某种程度上是特殊的,但这也没有帮助。我该怎么做才能创建这样的界面?

当然我想避免必须在派生类中使用两个操作数来实现调用操作符模板,因为派生类是框架的用户应该提供的内容,我想制作他的生活尽可能简单。

0 个答案:

没有答案
相关问题