Derived from template class? - c++

I'm trying to use the following code, but can't get it to complete.
Can anyone see the problem?
class IResourceJob
{
public:
virtual ~IResourceJob() {}
virtual void execute() = 0;
};
template<typename T>
class ResourceJob : public IResourceJob
{
public:
void execute()
{
static_assert(false, "Specialised ResourceJob<T> not defined!");
}
};
template<>
class ResourceJob<int>
{
public:
void execute()
{
// test.
}
};
The following usage gives a compile error:
IResourceJob* job = new ResourceJob<int>;
Thanks!

The compiler gives an error for any template that can never be instantiated. For your member function of the class template (i assume you mean static_assert), that is true, so the compiler is in right to give you a diagnostic.
You want to make the condition depend on T and cleverly make it always evaluate to false when instantiated. For example like
template<typename T>
struct always_false : std::false_type {};
template<typename T>
class ResourceJob : public IResourceJob
{
public:
void execute()
{
static_assert(always_false<T>::value,
"Specialised ResourceJob<T> not defined!");
}
};
Since the compiler cannot know whether the user will put a specialization of always_false (which you won't, of course), it cannot early-reject the template anymore.
I also doubt that you wanted to put the static_assert into execute, since your error message indicates that ResourceJob as a whole needs to be specialized. So put the static_assert outside of the member function into the class body. If you don't want the user to specialize the whole template, but only the member function, the user instead needs to say
// either "inline" and in the header, or not "inline" and in the .cpp file, but then
// put this into the header: template<> void ResourceJob<int>::execute();
template<> inline void ResourceJob<int>::execute() {
}
This will provide an alternative definition of execute which will be used by the template if T is int.

IResourceJob* job = new ResourceJob<int>;
fails because the class ResourceJob<int> is not derived from from IResourceJob.
The code should be
template<>
class ResourceJob<int> : public IResourceJob
{
public:
void execute()
{
// test.
}
};

You need to derive the template specialization as well, as in:
template<>
class ResourceJob<int> : public IResourceJob
{ /* ... */ };

Related

How to call a template member function from the <class T> class

First my code, better to ask the question with code visible.
template<class T>
class TemplateClass
{
public:
TemplateClass()
{
};
~TemplateClass(){};
T cc{this};
void tbcFunction(){};
void otherFunction(){};
};
class CallerClass
{
public:
CallerClass(TemplateClass<CallerClass>* tc) : templatePointer(tc){};
~CallerClass(){};
TemplateClass<CallerClass>* templatePointer;
void myFunction()
{
templatePointer->tbcFunction();
};
};
void setup()
{
TemplateClass<CallerClass> ct;
ct.otherFunction();
}
I need to call a function from TemplateClass from the code in CallerClass.
One way to achieve that is to provide the "this" from TemplateClass to the CallerClass when instantiating.
That is the solution I have done above with passing it within the constructor.
Are there any negative effects when doing it this way ?
Are there other/better/more elegant solutions for this ?

C++ Static Polymorphism––Referencing Specialized Template Methods Overloaded In Derived Class From Base Class Pointer

I am implementing a variation of the observer pattern in C++. However, because of the nature of the nature of my project, it CANNOT USE ANY VIRTUAL MEMBER FUNCTIONS, as the aggregate overhead from vtable lookups and cache misses is unacceptable.
Were I to create interfaces via virtual member functions, I would trivially write the following:
template <class MessageType>
class MessageSubscriber {
public:
virtual void OnMessage(MessageType *message) = 0;
};
template <class MessageType>
class MessagePublisher {
public:
void AddSubscriber(MessageSubscriber<MessageType> *subscriber) {
subscribers.push_back(subscriber);
}
protected:
void Publish(MessageType *message) {
for (auto subscriber : subscribers)
subscriber.OnMessage(message);
}
private:
std::vector<MessageSubscriber<MessageType>*> subscribers;
};
Then, for example, I could have classes that implement MessageSubscriber for some MessageType, SafetyMessage, like so:
class SafetyMessageSubscriberA : public MessageSubscriber<SafetyMessage> {
public:
virtual void OnMessage(SafetyMessage *message) override {
/* process message */
}
};
class SafetyMessageSubscriberB : public MessageSubscriber<SafetyMessage> {
public:
virtual void OnMessage(SafetyMessage *message) override {
/* process message */
}
};
class SafetyMessagePublisher : public MessagePublisher<SafetyMessage> {
public:
void Run {
/* manipulate message data */
this->Publish(&message);
}
private:
SafetyMessage message;
};
This would get the job done, but, as emphasized earlier, the vtable lookup overhead is unacceptable in the context of the application despite the polymorphic convenience that it provides and is also needed for the application. Naturally, then, I tried several approaches centering around the static polymorphism that can be leveraged through templates.
I first tried to utilize CTRP, but it fails in this case because the pointers contained in MessagePublisher::subscribers must point to the same base class when MessagePublisher::Publish(MessageType *message) is called. Ergo, you could not have some CTRP pattern along the lines of MessageSubscriber<SafetyMessageSubscriberA>, MessageSubscriber<SafetyMessageSubscriberB>, as the template arguments would need to be the same for both objects to legally be allowed in MessagePublisher::subscribers.
My most recent attempt at the problem has lead me to try some variations of member function template specialization, albeit unsuccessfully. I have tried the following variation on the pattern interface:
class MessageSubscriber {
public:
template <class MessageType>
void OnMessage(MessageType *message);
};
class MessagePublisher {
public:
template <class MessageType>
void Publish(MessageType *message) {
for (auto subscriber: subscribers)
subscriber->OnMessage<MessageType>(message);
}
private:
std::vector<MessageSubscriber*> subscribers;
};
template<class MessageType>
void MessageSubscriber::OnMessageOnMessage(MessageType *message) {
/* "interface" call; do nothing */
}
With implementations such as:
class SafetyMessageSubscriberA : public MessageSubscriber {
public:
// declare for legal overload
template <class MessageType>
void OnMessage(MessageType *message);
};
class SafetyMessageSubscriberB : public MessageSubscriber {
public:
// declare for legal overload
template <class MessageType>
void OnMessage(MessageType *message);
};
template<>
void SafetyMessageSubscriberA::OnMessage<SafetyMessage*>OnMessage(SafetyMessage *message) {
/* process message */
}
template<>
void SafetyMessageSubscriberB::OnMessage<SafetyMessage*>OnMessage(SafetyMessage *message) {
/* process message */
}
When I tried this, however, MessagePublisher::Publish(SafetyMessage *message) would always call the generic MessageSubscriber::OnMessage(MessageType *m)implementation for the base class, not the ones that were implemented for the derived classes specific to SafetyMessage*.
Am I incorrectly specializing the function templates as intended, or is there another more efficient solution? I apologize in advance for any imprecise wording as it relates to the concepts of overloading and member template specialization.
You can cut out one level of indirection by using C-style function pointers in place of virtual functions. Thus, in the declaration of your base class you might have something like:
void (*) OnMessage (BaseClass *self, MessageType *message);
You then initialise this instance variable in each of your derived classes' constructors to point to the appropriate static member function, which in turn allows you to call it via a single indirect call (as opposed to two if you went via the vtable).
Finally, sadly, you will need to cast self in each of the target functions in the derived classes, which is the price you pay for all this trickery. Either that or cast the function signature when assigning the function pointer. I will post a fuller example if interested - let me know.

Force template static member instantiation

I'm trying to create the program that executes some code only if the template is instantiated (it will be used for low-level driver initialization).
Now I have the following solution.
class Initializer
{
public:
Initializer(){
// This code is executed once
}
void silly() const{
}
};
template <class T>
class Proxy{
protected:
static const Initializer init;
};
template<class T>
const Initializer Proxy<T>::init;
template<class T>
class MyTemplate : public Proxy<void>{
public:
static void myMethod1(){
init.silly();
// ... Something useful
}
static void myMethod2(){
init.silly();
// ... Something useful
}
};
The Initializer default constructor is executed only in case I call myMethod1() or myMethod2() somewhere.
But is there a way to get rid of those init.silly(); lines?
Your problem, is that members of a template are not instantiated unless they are referenced.
Rather than calling init.silly(), you can just reference the member:
static void myMethod1(){
(void)init;
// ... Something useful
}
Or, if you want init to be defined absolutely always, you can explicitly instantiate it:
template<>
const Initializer Proxy<void>::init{};
template and low-level driver initialization?.. I'd try to make it as C as possible :) to ensure exact behavior.
You can do something like this perhaps:
class Initializer
{
public:
Initializer() {
// This code is executed once
}
};
template <class T>
class Proxy {
protected:
Proxy()
{
static Initializer init;
}
};
template<class T>
class MyTemplate : public Proxy<void> {
public:
void myMethod1() {
// ... Something useful
}
void myMethod2() {
// ... Something useful
}
};
All your code uses only static functions and doesn't really show why you would use classes and templates. With my change I made myMethod1 and myMethod2 non static and Proxy() constructor would create Initializer once.
Note that because of all that template mess your Initializer might be executed as many times as you instantiate Proxy template. Did you really mean it? If not, convert to clear readable code that doesn't have this unexpected results. This will also be better maintainable and readable for others:
class Initializer
{
Initializer() {
// This code is executed once
}
public:
void init()
{
static Initializer init;
}
};
template<class T>
class MyTemplate {
public:
static void myMethod1() {
Initializer::init();
// ... Something useful
}
static void myMethod2() {
Initializer::init();
// ... Something useful
}
};
This makes it absolutely clear that Initializer will be created only once just before myMethod1 or myMethod2 is called. If nothing calls your Initializer::init then that code from Initializer should be removed at link time.

Double partial template specialization for a class

I've stumbled upon a little problem with a little code I'm doing while learning c++11/14. Basically I have a Debugging class which I want to handle all the message printing. Most debugging/logging classes have log levels of sorts, but I want to use a flag for each message I have.
For that I have a little enum where I define my flags and their values:
enum DebugFlag {
Flag1 = 0,
Flag2 = 1,
Flag3 = 2
};
Aditionally, I have a Debugging class, which I've managed to specialize for Flag types and it works pretty well.
template<DebugFlag T>
class Debug {
public:
template <typename U>
static void print(U &&arg) {}
};
template <>
class Debug<static_cast<DebugFlag>(1)> {
public:
static void print(std::string &&message) {
std::cerr<<message<<"\n";
}
static void print(std::ostream &message) {
std::cerr<<DebugStream()().str()<<"\n";
DebugStream()().str("");
DebugStream()().clear();
}
static void print(std::string &message) {
std::cerr<<message<<"\n";
}
};
To call this class, I use a call like:
Debug<Flag1>::print("Message\n"); // should not do anything with Flag1 compiled to 0 value
Debug<Flag2>::print("Message\n"); // should work
Now I wanted to expand this class to also take bool values, so calls like this will work:
Debug< Flag2<2 >::print("Message\n"); // should not do anything with Flag1 compiled to 2 value
Debug< Flag2<1 >::print("Message\n"); // should work
The problem is I need a second partial specialization for my Debug class, that is bool, and I can't figure exactly what the syntax is for this.
This is the closest I've come to it, but still can't figure out what I'm doing wrong or if it's possible without making a secondary class and changing the way I want my call to look like: http://cpp.sh/6yemn
I don't understand exactly how you want to be able to use your class, but here's something that works.
template <typename T, T v = T()>
class Debug {};
template <>
class Debug<Flag, Flag2> {
public:
void f() { std::cout<<"This is good\n"; }
};
template <>
class Debug<bool, true> {
public:
void f() { std::cout<<"This is good too\n"; }
};
The problem is that you need to specify the type : whether you want to use a bool or a Flag, and then the value. You can instantiate the class like so :
Debug<bool, true> trueDebug;
Debug<Flag, Flag2> flag2Debug;
Other instances won't have the f function unless you add a specialization. For example :
template <Flag v>
class Debug<Flag, v> {
public:
void f() { std::cout<<"This is bad\n"; }
};
Live example

recursive c++ template problem

Say I have a template class that takes msgs from source, does something smart to them, and then sends them to a sink:
template <typename Source, typename Sink>
class MsgHandler
{
MsgHandler(Source* pSource)
: m_pSource(pSource)
{
m_pSource->setHandler(this);
}
};
//Now the definition of the Source:
template <typename Handler>
class Source
{
void setHandler(Handler* pHandler)
{
m_pHandler = pHandler;
}
};
All fine, but now I can't really make a Source or Handler. Eg:
MsgHandler<FileSource<MsgHandler<FileSource.... recursing parameters...
FileSource<MsgHandler<FileSource<MsgHandler.... same problem when trying to build a source
Is there a way to solve this problem without using a virtual base class for the Handler?
Virtual base class solution:
class MyHandler
{
virtual ~MyHandler() {};
virtual void handleSomething() = 0;
};
template <typename Source, typename Sink>
class MsgHandler : public MyHandler
{
MsgHandler(Source* pSource)
: m_pSource(pSource)
{
m_pSource->setHandler(this);
}
void handleSomething() {}
};
class Source
{
void setHandler(MyHandler* pHandler)
{
m_pHandler = pHandler;
}
};
You could use a templated parameter for the source parameter of your handler:
class MySink;
template <template<typename Handler> class Source, typename Sink>
class MsgHandler
{
Source<MsgHandler>* m_pSource;
MsgHandler(Source<MsgHandler>* pSource)
: m_pSource(pSource)
{
m_pSource->setHandler(this);
}
};
//Now the definition of the Source:
template <typename Handler>
class Source
{
void setHandler(Handler* pHandler)
{
m_pHandler = pHandler;
}
};
//Now you can define variables like this
MsgHandler<Source, MySink> myHandler;
Of course that requires the Source parameter of MsgHandler to be a template with exactly one parameter (the handler), but if you can live with that constraint this would solve your definition problem (otherwise you might (or might not depending on what exactly you would be trying) be able to use some extra template foo to circumvent this restriction (creating another template which takes the handler as parameter and has a typedef for the corresponding SourcesType comes to mind).
In this scenario it might also be a good idea to add an typedef Source<MsgHandler> SourceType to MsgHandler to make the Source-Instantiation visible to the caller (instead of requiring the programmer to guess that MsgHandler will instantiate Source.
I don't understand why your Source needs to be parameterized on its handler. If Source and Handler really do need to be tightly coupled in the way you describe, it does not seem like templates buy you very much beyond interface definition. Seems to me like you could just have a non-template Source class that encapsulates Handler<Source, Sink>.
It looks like the Handler shouldn't know anything about the Source. How about simple linear dependency:
template <typename Sink>
class Handler {
private:
Sink* sink; // get this pointer in the constructor?
public:
void handle( const Msg& m ) {
// processing
sink->accept( m );
}
};
template <typename Handler>
class Source {
private:
Handler* handler;
public:
void genMessage() {
Msg m;
// get message off the wire?
handler->handle( m );
}
};
Could also be twisted to have "handling" and "sinking" as policies.