Alex Rivera | Logout

Compiler warning at C++ template base class

Asked 2010-06-16T09:16:12.713
14

I get a compiler warning, that I don't understand in that context. When I compile the "Child.cpp" from the following code. (Don't wonder: I stripped off my class declarations to the bare minimum, so the content will not make much sense, but you will see the problem quicker). I get the warning with Visual Studio 2003 and Visual Studio 2008 on the highest warning level.


The code

AbstractClass.h:

#include <iostream>

template<typename T>
class AbstractClass
{
    public:
        virtual void Cancel(); // { std::cout << "Abstract Cancel" << std::endl; };
        virtual void Process() = 0;
};

// Outside definition. If I comment out this and take the inline
// definition like above (currently commented out), I don't get
// a compiler warning.
template<typename T>
void AbstractClass<T>::Cancel()
{
    std::cout << "Abstract Cancel" << std::endl;
}

Child.h:

#include "AbstractClass.h"

class Child : public AbstractClass<int>
{
    public:
        virtual void Process();
};

Child.cpp:

#include "Child.h"
#include <iostream>

void Child::Process()
{
    std::cout << "Process" << std::endl;
}

The warning

The class "Child" is derived from "AbstractClass". In "AbstractClass" there's the public method "AbstractClass::Cancel()". If I define the method outside of the class body (like in the code you see), I get the compiler warning...

AbstractClass.h(7) : warning C4505: 'AbstractClass::Cancel' : unreferenced local function has been removed with [T=int]

Edit
Report

1 Answer

6

I don't see the correct answer anywhere here: if you have a pure virtual method in a templated class, Visual Studio incorrectly reports this warning. Other compilers, like gcc and clang, do not appear to report this warning in this case.

Pure virtual methods in templated or non-templated classes are perfectly reasonable, and often a good idea - declaring the method as pure virtual forces you to implement it in derived classes.

I didn't find a reference to this anywhere as a bug - I'm not in a Microsoft developer program, perhaps someone who is could file this bug?

answered 2012-01-09T19:30:01.233

Your Answer