c++中的编译错误

compilation error in C++

本文关键字:错误 编译 c++      更新时间:2023-10-16

我在c++中有以下代码,我得到了编译错误:

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"

请帮我找出这里出了什么问题。非常感谢。

#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;
};

Derived<>::run()中,更改

d.operator()<int>();

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

有关详细信息,请参阅本FAQ:
->template.template::template的语法是关于什么的?

当使用Visual Studio 2008附带的Microsoft c++ Compiler version 15.00.21022.08编译时,您的原始版本可以工作,并伴有以下消息:

C:Program FilesMicrosoft Visual Studio 9.0VCINCLUDExlocale(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