简体   繁体   中英

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()" << std::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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM