473,769 Members | 7,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Instansing singleton right in the header file

I need to have one object for each template argument(s) used. For
example, I need to have one object of int. I tried the following code
and it gives me all I want with Visual C++ 7.1. But is it portable???
Will all compilers produce code that prints "single"?

Instancing of object right in header file (that can be include multiple
times - i.e. in multiple cpp files) give rise to my doubts...
Singleton.cpp
----------------------
#pragma once
template <typename T>
class Singleton
{
public:
static T * GetInstance()
{
static T Instance;
return &Instance;
}
};
First.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * First()
{
return Singleton<int>: :GetInstance();
}

void * Second();

int main()
{
std::cout << (First() == Second() ? "single" : "multiple" );
std::cout << std::endl;
return 0;
}
Second.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * Second()
{
return Singleton<int>: :GetInstance();
}

Mar 17 '06 #1
3 5742
Raider wrote:
I need to have one object for each template argument(s) used. For
example, I need to have one object of int. I tried the following code
and it gives me all I want with Visual C++ 7.1. But is it portable???
Of course.
Will all compilers produce code that prints "single"?
All compliant ones will.
Instancing of object right in header file (that can be include multiple
times - i.e. in multiple cpp files) give rise to my doubts...
You're not instantiating it "in header file". You're instantiating it
in a function. By the time the function is generated, compiled, and
then executed, there are no header files (reminds me of "there is no
spoon" from the Matrix movie).
Singleton.cpp
----------------------
#pragma once
template <typename T>
class Singleton
{
public:
static T * GetInstance()
{
static T Instance;
return &Instance;
}
};
First.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * First()
{
return Singleton<int>: :GetInstance();
}

void * Second();

int main()
{
std::cout << (First() == Second() ? "single" : "multiple" );
std::cout << std::endl;
return 0;
}
Second.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * Second()
{
return Singleton<int>: :GetInstance();
}


V
--
Please remove capital As from my address when replying by mail
Mar 17 '06 #2
Raider wrote:
I need to have one object for each template argument(s) used. For
example, I need to have one object of int. I tried the following code
and it gives me all I want with Visual C++ 7.1. But is it portable???
Will all compilers produce code that prints "single"?

Instancing of object right in header file (that can be include multiple
times - i.e. in multiple cpp files) give rise to my doubts...
Absent the export keyword (which itself is not very portable at the
moment), templates *must* be defined in the header file. The
compiler/linker will make sure there is actually only one instance in
the the final product.
Singleton.cpp
----------------------
#pragma once
Non-standard. Prefer #ifndef include guards.
template <typename T>
class Singleton
{
public:
static T * GetInstance()
{
static T Instance;
return &Instance;
}
};
You might consider returning a reference and disabling some other
functions just for safety:

private:
Singleton();
Singleton( const Singleton& );
Singleton& operator=( const Singleton& );
Singleton* operator&();
~Singleton();
First.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * First()
{
return Singleton<int>: :GetInstance();
}

void * Second();

int main()
{
std::cout << (First() == Second() ? "single" : "multiple" );
std::cout << std::endl;
return 0;
}
Second.cpp
----------------------
#include <iostream>
Unnecessary here.
#include "Singleton. h"

void * Second()
{
return Singleton<int>: :GetInstance();
}


Cheers! --M

Mar 17 '06 #3
Raider wrote:
I need to have one object for each template argument(s) used. For
example, I need to have one object of int. I tried the following code
and it gives me all I want with Visual C++ 7.1. But is it portable???
Will all compilers produce code that prints "single"?

Instancing of object right in header file (that can be include multiple
times - i.e. in multiple cpp files) give rise to my doubts...
Singleton.cpp
----------------------
#pragma once
template <typename T>
class Singleton
{
public:
static T * GetInstance()
{
static T Instance;
return &Instance;
}
};
First.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * First()
{
return Singleton<int>: :GetInstance();
}

void * Second();

int main()
{
std::cout << (First() == Second() ? "single" : "multiple" );
std::cout << std::endl;
return 0;
}
Second.cpp
----------------------
#include <iostream>
#include "Singleton. h"

void * Second()
{
return Singleton<int>: :GetInstance();
}


The code is not portable because it's using #pragma once instead of
standard header guards.
I'm guessing that Singleton.cpp is a typo, since it should be
Singleton.h

If you have a limitted set of types you want to use with your Singleton
template class, there is a way to put the implementation inside a *.cpp
file (even if you don't have export keyword support).
You can do template forward declaration.
Example:
//Your Singleton.cpp
template Singleton<int>;
template Singleton<std:: string>;
#include "foofoo.h"
template Singleton<foofo o>;
//Your Singleton implementation here
If you have the above code in the Singleton.cpp file, than you can
create an instance of your Singleton template of type int, std::string,
or foofoo.
If you used a different type, than you would get a linker error.
This method is only usefull if you're only going to support limitted
types for your Singleton template.

Mar 17 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4789
by: tarmat | last post by:
I have a singleton class that looks a little like this: class MyClass { private: //data MyClass() {
10
2655
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
6
3020
by: Tony Johansson | last post by:
Hello! I have a class called Outdoors which is a singleton see below for definition and a main that call this instance method. Now to my problem this piece of code doesn't compile I get the following error I can't understand what it is. start.obj : error LNK2001: unresolved external symbol "private: __thiscall Outdoors::Outdoors(void)" (??0Outdoors@@AAE@XZ) Debug/slask.exe : fatal error LNK1120: 1 unresolved externals
5
4716
by: LinuxGuy | last post by:
Hi, I have come across singleton class with some member variables are declared as static with public scope. As singleton class always return only one instance. ie. single copy of object is maintained all the time. can someone tell me the reason behind declaring those variables as static one.
3
1405
by: Jeremy Cowles | last post by:
Will the keyword "Me" ever be able to be the target of an assignment? Because singleton classes would be MUCH simplier if you could just point Me to a different address. For example: Class SingletonClassic Private Shared sm_Instance as SingletonClassic Public Shared Sub GetInstance() Return sm_Instance End Sub
5
1744
by: Eric | last post by:
I am implementing a variation on the Singleton design pattern, that allows up to 8 objects of a class to be instantiated, and returns a null pointer for anything more than 8. I am running into a compile problem with GNU g++. Here is the code: /******************** FILE sample.h ********************/
8
1782
by: Frederick Gotham | last post by:
Let's say you want to write a simple header file, and don't want to be burdened with having to provide a source file as well with it. There's a problem when the need arises for a global object. You could simply make the object static... but then you'll have a separate object for each source file that includes the header. Do many people use a inline function to get around this? inline
5
2744
by: Markus Dehmann | last post by:
I need a Singleton for general program options so that all classes can access it. I use the code below (adapted from the Wikipedia singleton example). But the problem is if I change one variable in it, all my classes have to re-compile. But I am planning to add more options often during development. I tried to solve it through a forward declaration "class Opts;", but didn't succeed because Opts::instance() results in an error message...
1
4169
by: James Kanze | last post by:
On Apr 11, 12:09 am, Ron Eggler <t...@example.comwrote: That's usually a feature, not a bug, where singletons are concerned. In general, I avoid ever deleting a singleton. From the destructor of what?
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.