Singleton and constructors with arguments
| bomben (9) | |||
| Hi all, this is my first post and I hope this is going to be an easy one. I inherited well written but zero-commented code. And I was trying to understand how a particular piece of code works... 'cause it works perfectly.
You can use singleton in this way:
MyClass *aClass_ptr = Singleton<MyClass>::GetInstance();or
MyClass *aClass_ptr = Singleton<MyClass>::GetInstance(val1);or
MyClass *aClass_ptr = Singleton<MyClass>::GetInstance(val1, val2);The point is: how the singleton knows about MyClass-constructor arguments-type? Again: it works perfectly (and I've personally overloaded the version with 2 arguments!), but I do not understand how! :D Many many thanks in advance! Cheers, Marco | |||
| satm2008 (149) | |||
| Did you compile after you overloaded the constructors? Hmm I guess it gives you a couple of compiler errors as you made the overriding constructors inline but you coded them as you are coiding outside. Still I am not able to understand what you want to achieve here. Nested or template overloading kind of??? | |||
| bomben (9) | |||
| I compiled and run the program and it worked perfectly. I used a 'people' class, whose data members are a _name (std::string) and a _height (int). I defined 2 kinds of constructor: people(); people( std::string, int ); I created one 'people' in this way:
people* aPerson = Singleton<people>::GetIstance();but (in another program, 'cause the Singleton do works) also in this way:
people* aPerson = Singleton<people>::GetIstance( "Mark", 166 );And it gives me no error at all What I want is to have a Singleton that works for constructors taking one or more arguments. Thanks for being giving a look! Marco | |||
| vince1027 (82) | |||
| Templates are replaced during compile time. The compiler will map the functions of the specific class to the generics. The template class does not know nor even need to know the pre-conditions of your specific class. The compiler does this job. Try violating the pre-conditions and the compiler will complain. | |||
| jsmith (958) | |||
| The code in the original post will work for constructors that take zero, one, or two parameters. Under the current C++ standard there is no way to generalize the solution for N parameters (however in the next version of the standard variadic templates will solve the problem). The way the problem is typically solved today is to provide a bunch of templated functions that cover enough parameters:
| |||
| bomben (9) | |||
| Thank you all guys! Now it is much more clear. BTW, I discovered another case in which you can use templated methods w/o explicitely specifying type-arguments, the std::sort method:
http://www.cplusplus.com/reference/algorithm/sort.html | |||
This topic is archived - New replies not allowed.
