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; }
};
Related
I have a class that does something similar to:
class B{
void x(){
statement-block1;
statement-block2;
statement-block3;
statement-block4;
}
void y(){
statement-block5;
statement-block6;
statement-block7;
statement-block8;
}
}
I need to add a new class that does this:
class C{
void x(){
statement-block1;
statement-block200;
statement-block3;
statement-block4;
}
void y(){
statement-block5;
statement-block6;
statement-block700;
statement-block8;
}
}
I was considering combining the reusable logic this way:
class A{
void x(){
statement-block1;
statement-block2;
u();
statement-block4;
}
void y(){
statement-block5;
statement-block6;
v();
statement-block8;
}
virtual void u(){
default-message;
}
virtual void v(){
default-message;
}
}
class B : A{
void u(){
statement-block3;
}
void v(){
statement-block7;
}
}
class C : A{
void u(){
statement-block200;
}
void v(){
statement-block700;
}
}
Is there a better way to implement this, a different/better way of injecting sub-class-specific code, or is there a design pattern I can use? In the future, I might have to add more classes similar to B and C.
Thanks!
It depends what you are trying to achieve. If the statements block are likely to change in run time (dynamic) then use virtual pointer as you showed in your example, however if those are not dynamic, then pass a template parameter instead, in that way you don't pay for what you don't use (virtual pointer). i.e.
class B
{
public:
template <typename T>
void x(T f)
{
f();
}
};
void g(){ std::cout << "value" << std::endl;}
int main()
{
B b {};
b.x(g);
}
Your approach looks great. It applied KISS which is most often the best design pattern to use! You could do this
virtual void u(){
default-message;
}
virtual void v(){
u();
}
But that's up to you I guess
Another option is to combine all classes and use std function or a function pointer for that function call that changes.
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) { /* ... */ }
};
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); }
};
I would like to do something like:
class A {
public:
void f();
private:
void g() { };
};
class B {
public:
void f();
private:
void g() { };
};
template<typename T>
void T::f() {
g();
}
int main() {
A a;
B b;
a.f();
b.f();
}
however T::f() does not compile.
Possible workarounds could be making f() non-member:
template<typename T>
void f(T* t);
Or using CRTP: http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
But is there no C++ syntax to do as above?
EDIT: I have a big function f() whose code is shared by the 2 classes A and B. A and B have the same interface, which f() uses. However, because we are not using runtime polimorphism (i.e, virtual functions), the corpus of f() needs to be instantiated twice at compile time, once for A and once for B. Templates are made exactly for this purpose. The function f(), in my case, should be template function whose template type is the type of *this.
Free function is the correct answer. You should prefer free functions over member functions anyway, for this exact reason: you extend the interface without intruding on the class.
In this case, a free function with an unconstrained template is a bit ugly, because you only need it to work for two cases, not all cases. You should do something like this:
namespace detail
{
template <typename T>
void f(T* t)
{
// implement stuff
}
}
void f(A* x)
{
detail::f(x);
}
void f(B* x)
{
detail::f(x);
}
Now you can restrict access to that function via overloading.
Here is an example using a free function and retaining the instance.f() syntax. The function needs to be marked as a friend in order to access the private methods:
#include <iostream>
namespace details
{
template<class T>
static void f_impl(T* _this)
{
_this->g();
}
}
class A {
public:
template<class T> friend void details::f_impl(T*);
void f()
{
details::f_impl(this);
}
private:
void g()
{
std::cout << "A" << std::endl;
}
};
class B {
public:
template<class T> friend void details::f_impl(T*);
void f()
{
details::f_impl(this);
}
private:
void g()
{
std::cout << "B" << std::endl;
}
};
int main() {
A a;
B b;
a.f();
b.f();
}
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]