C ++模板类的成员函数中的类型/值不匹配

时间:2015-12-31 12:31:58

标签: c++ templates g++

我有一个与此类似的代码:

#include <iostream>

template<typename T> class Functor
{
    T *pthis;
    void (T::*fun)(void);
public:
    Functor(T* punteroThis, void (T::*funcion)() ) : pthis(punteroThis), fun(funcion) { }
    void operator() (void);
};

template<typename T>
void Functor<T>::operator() ()
{
    (pthis->*fun)();
}

template<typename T> class myTimer
{
    /*
       omitted 'typename' so that T inside task
       is the same as T in class myTimer
    */
    template<T> class task
    {
        unsigned id;
        bool active;
        Functor<T> fun;
        unsigned interval;
    public:
        task(unsigned id_, bool active_, Functor<T> fun_, unsigned interval_) : id(id_), active(active_), fun(fun_), interval(interval_) { }
    };


    void print(myTimer::task<T> const& t);    // << this is not working

};

template<typename T>
void myTimer<T>::print(myTimer::task<T> const& t)
{
    std::cout << "id = " << t.id << '\n';
    std::cout << "active = " << t.active << '\n';
    std::cout << "interval = " << t.interval << std::endl;
}

调用编译器时

g++ -Wall -g -std=c++11 myTimer.h -c

我在print()的声明和定义中都遇到以下错误:

error:   type/value mismatch at argument 1 in template parameter list for
      ‘template<class T> template<T <anonymous> > class myTimer<T>::task’
error:   expected a constant of type ‘T’, got ‘T’

我也试过了typename并获得了相同的输出。我不知道如何解决它。知道发生了什么事吗?

我在Linux平台上使用g ++版本4.8.4

1 个答案:

答案 0 :(得分:1)

此代码不正确:

/*
   omitted 'typename' so that T inside task
   is the same as T in class myTimer
*/
template<T> class task

如果您希望T inside任务与包含范围中的T相同,则完全忽略template<T>

然后你有:

void print(myTimer::task<T> const& t);    // << this is not working

你想要的地方:

void print(myTimer::task const& t);