That may sound kind of strange, and I may have to refactor my code at some point but I would need to generate the pure virtual base class methods with a template function. Is it doable with C++11 (variadic templates ?) ?
Example :
struct I
{
virtual void foo(int) = 0;
virtual void foo(float) = 0;
};
struct S : public I
{
template<typename T>
void foo(T t) { /*do the same symbolic stuff on t*/ }
};
int main()
{
S s;
s.foo(0);
s.foo(0.0f);
return 0;
}
Giving the following error (clang) :
main.cpp:65:7: error: variable type 'S' is an abstract class
S s;
^
main.cpp:53:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(int) = 0;
^
main.cpp:54:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(float) = 0;
^
1 error generated.
You can't do that.
A signature of a template method is not the same of a non-template method.
And you can't have a virtual template method.
You can't do it directly, but you can use forwarders to have a common implementation:
struct S : public I
{
private:
template<typename T>
void foo_impl(T t) { /*do the same symbolic stuff on t*/ }
public:
virtual void foo(int v) { foo_impl(v); }
virtual void foo(float v) { foo_impl(v); }
};
Related
I am trying to implement an abstract class (ElementHolder) over a Template (TElementHolder). The function virtual T* Fun2() seems to work fine but the function virtual void Fun(T* element); creates the following compile error:
source>:60:23: error: cannot declare variable 'fireHolder' to be of abstract type 'FireElementHolder'
60 | FireElementHolder fireHolder;
| ^~~~~~~~~~
<source>:51:7: note: because the following virtual functions are pure within 'FireElementHolder':
51 | class FireElementHolder : public TElementHolder<Fire>
| ^~~~~~~~~~~~~~~~~
<source>:22:22: note: 'virtual void ElementHolder::Fun(Element*)'
22 | virtual void Fun(Element* element) = 0;
|
Can someone explain to me why the two functions create different results?
And if I can make this work somehow?
I am not sure if Implementing a pure virtual function over a template is the correct way of saying what I am doing here.
source: https://godbolt.org/z/qEYdrYfYa
#include <iostream>
//------------------------------------------------------------------------------------------
class Element
{
public:
virtual ~Element() {}
virtual void Fun() = 0;
};
class Fire : public Element
{
public:
~Fire() {}
void Fun() { std::cout << "Fire" << std::endl; }
};
//------------------------------------------------------------------------------------------
class ElementHolder
{
public:
virtual ~ElementHolder() {}
virtual void Fun(Element* element) = 0;
virtual Element* Fun2() = 0;
};
template<class T>
class TElementHolder : public ElementHolder
{
public:
virtual ~TElementHolder();
virtual void Fun(T* element);
virtual T* Fun2();
};
template<class T>
TElementHolder<T>::~TElementHolder() {}
template<class T>
void TElementHolder<T>::Fun(T* element)
{
element->Fun();
}
template<class T>
T* TElementHolder<T>::Fun2()
{
std::cout << "Hello Fun2" << std::endl;
return new T();
}
class FireElementHolder : public TElementHolder<Fire>
{
};
//------------------------------------------------------------------------------------------
int main()
{
FireElementHolder fireHolder;
auto instance = fireHolder.Fun2();
fireHolder.Fun(instance);
instance->Fun();
}
There is a well-known problem with your design.
You have two parallel class hierarchies, Elements and ElelementHolders. You want each concrete ElementHolder to accept a pointer or reference to a corresponding Element. So you add a pure virtual function to the base class
class ElementHolder {
virtual void Fun(Element* element) = 0;
and override it in each derived class (I de-templatized your hierarchy for ease of exposition, there is a T instead of Fire in your code, but it doesn't really affect anything):
class FireHolder : public ElementHolder {
virtual void Fun(Fire* fire) { ... }
Which is a very natural and sensible choice.
Except that it doesn't work at all, because void Fun(Fire* fire) doesn't override void Fun(Element* element). They are completely independent functions.
Now how do you solve this problem? There are two very different ways.
Get rid of ElementHolder::Fun altogether.
Change void Fun(Fire* fire) to void Fun(Element* fire). Cast fire to Fire* inside.
How does one cope without ElementHolder::Fun? Simply, just don't call it ;) You cannot safely use it anyway. The signature Fun(Element*) says that any element can be passed. In fact you can only pass Fire* to a FireHolder, and any other element is an error (so the signature lies---not a good idea). If you only have an ElementHolder and an Element *, there is no guarantee you can call Fun.
If you absolutely must call ElementHolder::Fun, then #2 is your only option.
I'm wondering whether it's possible to implement an "interface"'s function via member function templates like so:
struct VisitorI
{
virtual void Visit(int) = 0;
virtual void Visit(float) = 0;
};
struct VisitorC : public VisitorI
{
template<class T>
void Visit(T) { /*Assume Visit(T) has syntatically the same implemenation for each relevant T */}
};
template void VisitorC::Visit(int);
template void VisitorC::Visit(float);
int main()
{
VisitorC Visitor;
return 0;
}
The above code doesn't compile because foo(int) and foo(float) are considered pure virtual in VisitorC, so I'm thinking it's not possible. I don't really see any particular reason why it shouldn't though...?
Cheers,
Damian
As a workaround, you could:
struct VisitorC : public VisitorI
{
virtual void Visit(int a) { Visit_impl(a); }
virtual void Visit(float a) { Visit_impl(a); }
private:
template<class T>
void Visit_impl(T) { /* ... */ }
};
This issue involves using templates to resolve virtual members in a Dispatch pattern.
Note: This is not the same as virtual template method questions already asked on StackOverflow. *
Edit 1: Corrected syntax errors, added clarifications.
Given the following:
#include <string>
#include <iostream>
class Field_Interface
{
public:
virtual std::string get_field_name(void) const = 0;
};
class Field_Integer : public Field_Interface
{
public:
std::string get_field_name(void) const
{ return "INT";}
};
class Field_String : public Field_Interface
{
public:
std::string get_field_name(void) const
{ return "VARCHAR";}
};
class Field_Double : public Field_Interface
{
public:
std::string get_field_name(void) const
{ return "DOUBLE";}
};
class Abstract_Visitor
{
public:
virtual void visit(const Field_Integer& fi) = 0;
virtual void visit(const Field_String& fi) = 0;
virtual void visit(const Field_Double& fi) = 0;
};
class Visitor_Name_Query_1 : public Abstract_Visitor
{
public:
template <class Field>
void visit(const Field& f)
{
std::cout << "Field name is: "
<< f.get_field_name()
<< "\n";
}
};
class Visitor_Name_Query_2 : public Abstract_Visitor
{
public:
void visit(const Field_Integer& fi)
{ print_field_name(fi); }
void visit(const Field_String& fi)
{ print_field_name(fi); }
void visit(const Field_Double& fi)
{ print_field_name(fi); }
private:
void print_field_name(const Field_Interface& fi)
{
std::cout << "Field name is: "
<< fi.get_field_name()
<< "\n";
}
};
int main(void)
{
Visitor_Name_Query_1 q1;
Field_Integer fi;
q1.visit(f1);
return 0;
}
The compiler is saying the templated method in Visitor_Name_Query_1 is not resolving the abstract interface from Abstract_Visitor.
Edit 2: Results from g++
# g++ -o main.exe main.cpp
main.cpp: In function `int main()':
main.cpp:75: error: cannot declare variable `q1' to be of type `Visitor_Name_Query_1'
main.cpp:75: error: because the following virtual functions are abstract:
main.cpp:35: error: virtual void Abstract_Visitor::visit(const Field_Integer&)
main.cpp:36: error: virtual void Abstract_Visitor::visit(const Field_String&)
main.cpp:37: error: virtual void Abstract_Visitor::visit(const Field_Double&)
main.cpp:77: error: `f1' undeclared (first use this function)
main.cpp:77: error: (Each undeclared identifier is reported only once for each function it appears in.)
Visitor_Name_Query_1 is an attempt to simplify the class Visitor_Name_Query_2. When the number of visit methods grows beyond a simple quantity (like 5), maintenance becomes tedious. This is the reason for the template declaration.
When the template is expanded, with one of the field types, the declaration matches the one in Visitor_Name_Query_2.
So why is the compiler generating saying that class Visitor_Name_Query_1 is abstract?
Note: I am using Visual Studio 2008 on Windows Vista.
* The other posts involve using templates to create virtual method declarations. I'm using templates to create functions that implement the abstract methods.
So why is the compiler generating saying that class Visitor_Name_Query_1 is abstract?
Because the standard says so. §14.5.2 [temp.mem]/p4:
A specialization of a member function template does not override a
virtual function from a base class. [ Example:
class B {
virtual void f(int);
};
class D : public B {
template <class T> void f(T); // does not override B::f(int)
void f(int i) { f<>(i); } // overriding function that calls
// the template instantiation
};
—end example ]
It seems you really want the Abstract_Visitor to have a default implementation. If you move the template into the Abstract_Visitor, you can let each virtual visitor have the default implementation.
class Abstract_Visitor
{
template <class Field>
void visit(const Field& f)
{
std::cout << "Field name is: "
<< f.get_field_name()
<< "\n";
}
public:
virtual void visit(const Field_Integer& fi) { visit<>(fi); }
virtual void visit(const Field_String& fi) { visit<>(fi); }
virtual void visit(const Field_Double& fi) { visit<>(fi); }
};
As all field types have a common interface, you could simplify the problem by changing the interface if it is possible:
class Abstract_Visitor
{
public:
virtual void visit(const Field_Interface& f) = 0;
};
class Visitor_Name_Query_3 : public Abstract_Visitor
{
public:
void visit(const Field_Interface& f)
{
std::cout << "Field name is: "
<< f.get_field_name()
<< "\n";
}
};
I have this interface:
struct I
{
virtual void f(int) = 0;
virtual void f(float) = 0;
};
May I implemnt I using something similar to next class?
struct C : public I
{
template<typename T>
void f(T);
};
No, you can't do that. The template method overloads the original two methods (i.e. it's a different method with the same name). C still has two pure virtual functions.
As properly pointed out by NPE, you can't do this directly. However, you still can avoid code duplication by delegation:
struct C : public I
{
void f(int x) { f_internal(x); }
void f(float x) { f_internal(x); }
private:
template<typename T>
void f_internal(T x) { do stuff with x; }
};
In a typical implementation of the Visitor pattern, the class must account for all variations (descendants) of the base class. There are many instances where the same method content in the visitor is applied to the different methods. A templated virtual method would be ideal in this case, but for now, this is not allowed.
So, can templated methods be used to resolve virtual methods of the parent class?
Given (the foundation):
struct Visitor_Base; // Forward declaration.
struct Base
{
virtual accept_visitor(Visitor_Base& visitor) = 0;
};
// More forward declarations
struct Base_Int;
struct Base_Long;
struct Base_Short;
struct Base_UInt;
struct Base_ULong;
struct Base_UShort;
struct Visitor_Base
{
virtual void operator()(Base_Int& b) = 0;
virtual void operator()(Base_Long& b) = 0;
virtual void operator()(Base_Short& b) = 0;
virtual void operator()(Base_UInt& b) = 0;
virtual void operator()(Base_ULong& b) = 0;
virtual void operator()(Base_UShort& b) = 0;
};
struct Base_Int : public Base
{
void accept_visitor(Visitor_Base& visitor)
{
visitor(*this);
}
};
struct Base_Long : public Base
{
void accept_visitor(Visitor_Base& visitor)
{
visitor(*this);
}
};
struct Base_Short : public Base
{
void accept_visitor(Visitor_Base& visitor)
{
visitor(*this);
}
};
struct Base_UInt : public Base
{
void accept_visitor(Visitor_Base& visitor)
{
visitor(*this);
}
};
struct Base_ULong : public Base
{
void accept_visitor(Visitor_Base& visitor)
{
visitor(*this);
}
};
struct Base_UShort : public Base
{
void accept_visitor(Visitor_Base& visitor)
{
visitor(*this);
}
};
Now that the foundation is laid, here is where the kicker comes in (templated methods):
struct Visitor_Cout : public Visitor_Base
{
template <class Receiver>
void operator() (Receiver& r)
{
std::cout << "Visitor_Cout method not implemented.\n";
}
};
Intentionally, Visitor_Cout does not contain the keyword virtual in the method declaration. All the other attributes of the method signatures match the parent declaration (or perhaps specification).
In the big picture, this design allows developers to implement common visitation functionality that differs only by the type of the target object (the object receiving the visit). The implementation above is my suggestion for alerts when the derived visitor implementation hasn't implement an optional method.
Is this legal by the C++ specification?
(I don't trust when some says that it works with compiler XXX. This is a question against the general language.)
oh, I see what you're after. Try something like this:
template < typename Impl >
struct Funky_Visitor_Base : Visitor_Base
{
// err...
virtual void operator()(Base_Int& b) { Impl::apply(b) }
virtual void operator()(Base_Long& b) { Impl::apply(b) }
virtual void operator()(Base_Short& b) { Impl::apply(b) }
virtual void operator()(Base_UInt& b) { Impl::apply(b) }
virtual void operator()(Base_ULong& b) { Impl::apply(b) }
// this actually needs to be like so:
virtual void operator()(Base_UShort& b)
{
static_cast<impl *const>(this)->apply(b)
}
};
struct weird_visitor : Funky_Visitor_Base<weird_visitor>
{
// Omit this if you want the compiler to throw a fit instead of runtime error.
template < typename T >
void apply(T & t)
{
std::cout << "not implemented.";
}
void apply(Base_UInt & b) { std::cout << "Look what I can do!"; }
};
That said, you should look into the acyclic visitor pattern. It has misunderstood visitors built into the framework so you don't have to implement functions for stuff you'll never call.
Funny thing is that I actually used something very similar to this to build an acyclic visitor for a list of types. I applied a metafunction that basically builds Funky_Visitor_Base and turns an operator (something with an apply() like I show) into a visitor for that complete list. The objects are reflective so the apply() itself is actually a metafunction that builds based on whatever type it's hitting. Pretty cool and weird actually.
In your derived visitor class, Visitor_Cout, the operator() template does not override the operator() in the Visitor_Base. Per the C++03 standard (14.5.2/4):
A specialization of a member function template does not override a virtual function from a base class. [Example:
class B {
virtual void f(int);
};
class D : public B {
template <class T> void f(T); // does not override B::f(int)
void f(int i) { f<>(i); } // overriding function that calls
// the template instantiation
};
—end example]