Jump to content
  • Advertisement
Sign in to follow this  
deadimp

Templated Constructors - Not possible???

This topic is 4608 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to create a templated contructor in a non-templated class, but it will not let me invoke the constructor (Dev-C++: "expected `,' or `;' before '<' token"). This is basically what I have:
class Test {
public:
  template<typename T>
 Test() {
  T x=5; //It's just an example
  cout << "Test::Test<T>: " << x-- << "\n";
 }
};
//And later on...
Test a<int>();
The reason I want it to be done in the constructor is so that I don't have to call it's registration function later on in another function (and yes, I'm aware of the risks there are with this). I'm figuring that this is all I can really do:
Test a((int)0);

Share this post


Link to post
Share on other sites
Advertisement
You can have templated constructors, but you can't use an explicit instantiation for the templated constructor parameters. The compiler has to be able to deduce the parameters from the arguments to the constructor.

Share this post


Link to post
Share on other sites
Quote:
Original post by deadimp
What's the named constructor idiom?



Something like this:

class Test {
public:
template <typename T>
static Test *Create() {
T x=5;
cout << "Test::Create " << x-- << "\n";
return new Test();
}

private:
Test() {

}

};

//And later on...
Test *a = Test::Create<int>();
delete a;

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by deadimp
Ah well... I'll just go back to using macros.
Thanks for the help.


But... you can do templates. But you have to let the compiler figure it out (if you pass 0 it will make it an int) as you can't have:

variabletype variable<sometype>(sometypeinstance);



C++

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!