C++: How can I do *this*?

General discussion for off-topic subjects.
User avatar
BackRaw
Senior Member
Posts: 527
Joined: Sun Jul 15, 2012 1:46 am
Location: Germany
Contact:

C++: How can I do *this*?

Postby BackRaw » Mon Mar 04, 2019 2:24 pm

Hi,

I'm trying to do the following C++ template thing:

Syntax: Select all

template <class T>
T *do_stuff(const char *key, T::type default_value, bool required = false)
{
Base *o = new T(key, default_value, required);

...
}

Base constructor does not have the default_value parameter, but T must have it, so I can't use polymorphism.

I'm interested in how I could do the T::type thing. I know this is possible, but I don't know how to do it. I tried

Syntax: Select all

// within T type
using type = int;
but that doesn't work. VS 2017 complains with 'T::type': dependent name is not a type which is fine, because the compiler can't know that T::type exists.

Could I use the Base class somehow? Any clues?
User avatar
L'In20Cible
Project Leader
Posts: 1165
Joined: Sat Jul 14, 2012 9:29 pm
Location: Québec

Re: C++: How can I do *this*?

Postby L'In20Cible » Mon Mar 04, 2019 7:07 pm

You need to explicitly declare it as a type:

Syntax: Select all

#include <iostream>

class Base
{

};

class Class : Base
{
public:
// within T type
using type = int;
};

template <class T>
T* do_stuff(const char* key, typename T::type default_value, bool required = false)
{
std::cout << key << " Our default value is: " << default_value;
return NULL;
}

int main()
{
do_stuff<Class>("Hey!", 10, true);
}


Code: Select all

F:\test\Debug>test.exe
Hey! Our default value is: 10
F:\test\Debug>test.exe>pause
Press any key to continue . . .
User avatar
BackRaw
Senior Member
Posts: 527
Joined: Sun Jul 15, 2012 1:46 am
Location: Germany
Contact:

Re: C++: How can I do *this*?

Postby BackRaw » Tue Mar 05, 2019 12:33 am

Yep, that worked. Thank you!

Return to “Whatever”

Who is online

Users browsing this forum: No registered users and 2 guests