3
prog.cpp:9:13: error: ‘result_type’ does not name a type
prog.cpp:9:13: note: (perhaps ‘typename std::unary_function<_Arg, _Result>::result_type’ was intended)

编译器:http: //ideone.com/vttG8W

为什么我不能直接使用 result_type?

#include <functional>

using namespace std;

template <typename ARGUEMENT, typename RESULT>
class FunctorBase : public std::unary_function<ARGUEMENT, RESULT>
{
public:
    virtual result_type operator () (argument_type) = 0;
        FunctorBase() {}
        virtual ~FunctorBase() {}
};

int main()
{
    FunctorBase<int&, void>();
}
4

3 回答 3

3

因为result_typeargument_type依赖于模板参数。采用:

virtual typename std::unary_function<ARGUEMENT, RESULT>::result_type
  operator () (typename std::unary_function<ARGUEMENT, RESULT>::argument_type) = 0;

或者,如果您在更多地方需要它,请添加

using typename std::unary_function<ARGUEMENT, RESULT>::result_type;
using typename std::unary_function<ARGUEMENT, RESULT>::argument_type;

在你上课的开始。

于 2013-03-21T16:22:14.153 回答
3

因为它是一个不合格的名字

当您在类模板中使用非限定名称时,您必须告诉编译器它不应该在两阶段名称查找的第一阶段立即搜索全局名称,而是等到实例化(因为名称可能来自基类,就像这里的情况一样)。

在这种情况下,您可以这样做(并创建result_type一个从属的限定名称):

typedef typename std::unary_function<ARGUEMENT, RESULT>::result_type result_type;

请注意,这同样适用于argument_type.

typedef typename std::unary_function<ARGUEMENT, RESULT>::argument_type argument_type;

有了这两个typedefs,原始的成员函数声明现在将编译:

virtual result_type operator () (argument_type) = 0;
于 2013-03-21T16:26:02.530 回答
0

您可以在您的课程中重新 typedef 它:

typedef typename std::unary_function<ARGUEMENT, RESULT>::result_type my_result_type;

(您甚至可以将其重命名为完全相同的名称)即使您继承的内容是私有的,这也可以工作。

编译

template <typename blah>
class MyTemplateBaseClass
{
    public: 
    typedef blah my_blah_typedef;
};

template <typename arg>
class DerivedFromTemplated : private MyTemplateBaseClass<arg>
{
public:
    //Either giving the full name:
    typename MyTemplateBaseClass<arg>::my_blah_typedef GetBlahType()
    {
        return typename MyTemplateBaseClass<arg>::my_blah_typedef();
    }

    //Or typedef-ing it locally:
    typedef typename MyTemplateBaseClass<arg>::my_blah_typedef my_blah_typedef;
    my_blah_typedef GetBlahType2()
    {
        return my_blah_typedef();
    }
};

int main()
{
    DerivedFromTemplated<int> test;
}
于 2013-03-21T16:28:56.320 回答