开发者

compilation error in C++

I have the following code in C++ and I got the compilation error:

a.cpp: In member function `virtual void Derived<T, D>::run(T&)':
a.cpp:13: error: expected primary-expression before "int"
a.cpp:13: error: expected `;' before "int"

Please help me find out what went wrong here. Thanks a lot.

#include <iostream>
template<typename T> struct Base
{
    virtual void run( T& ){}
    virtual ~Base(){}
};

template<typename T, typename D> struct Derived : public Base<T>
{
    virtual void run( T& t )
    {
        D d;
        d.operator()<int>();//nor does d.operator()<T>(); work
    }
};

template<typename T> struct X
{
    template<typename R>  X(const R& r)
    {
       std::cout << "X(R)" << std::endl;
       ptr = new Derived<T,R>(); 
    }

    X():ptr(0)
    { 
        std::cout << "X()" << st开发者_如何学God::endl; 
    }

    ~X()
    {
        if(ptr) 
        {
            ptr->run(data);
            delete ptr;
        }
        else
        {
            std::cout << "no ptr" << std::endl;
        }
    }

    Base<T>* ptr; 
    T data;
};

struct writer
{
    template<typename T> void operator()()
    { 
        std::cout << "T "<< std::endl;
    }
};

int main()
{
    {
        writer w;
        X<int> xi1((writer()));
    }
    return 0;
};


In Derived<>::run(), change

d.operator()<int>();

to

d.template operator()<int>();

For further information, see this FAQ:
What is the ->template, .template and ::template syntax about?


Your original version works when compiled with Microsoft C++ Compiler version 15.00.21022.08 that comes with Visual Studio 2008 with the following message:

C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : 
warning C 4530: C++ exception handler used, but unwind semantics are not enabled. 
Specify /EHsc 
Microsoft (R) Incremental Linker Version 9.00.21022.08 Copyright (C) Microsoft Corporation.  All rights reserved.

/out:a.exe a.obj
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜