Apr 24, 2020 at 9:10pm UTC
Have you tried compiling it yet? 😜
Apr 24, 2020 at 9:35pm UTC
I did, but it didn't work.
Apr 24, 2020 at 10:04pm UTC
Actually what’s the code?
Apr 24, 2020 at 10:08pm UTC
So the method inside the class if for strings, and the one outside the class I want for numbers like int, long, short, etc.
Apr 24, 2020 at 10:31pm UTC
Hum... I’m pretty sure you have to specialize the entire class since the function it’s self isn’t a template function. So you have to do
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
template <typename T>
class exampleClass
{
private :
T variable;
public :
exampleClass(T inVariable)
{
variable = inVariable;
}
int display()
{
return variable.length();
}
};
template <>
class exampleClass <int >
{
private :
int variable;
public :
exampleClass(int inVariable)
{
variable = inVariable
}
int display()
{
return variable;
}
};
Or you could make display() into a template function and then try
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
template <typename T>
class exampleClass
{
private :
T variable;
public :
exampleClass(T inVariable)
{
variable = inVariable;
}
template <class d_t = T>
int display()
{
return variable.length();
}
};
template <>
int exampleClass::display<int >()
{
return variable;
}
Edit: I’m pretty sure what I put for the first one isn’t even correct code. The second one might work though, feels a bit hackish though.
Edit2: I sorry if the code doesn’t work I don’t have a compiler rn so I’m kinda flying blind :/
Last edited on Apr 24, 2020 at 10:38pm UTC
Apr 25, 2020 at 12:46am UTC
You know, you could just use the example I gave you in your last post:
1 2 3 4 5 6 7
template <typename T>
int display(T value)
{
std::ostringstream ss{};
ss << value;
return ss.str().length();
}
This should work for int, long, std::string, const char*, etc. Furthermore, it also works for classes that have defined overloaded ostream operations. Or wrap it inside your class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
template <typename T>
class exampleClass
{
private :
T variable;
public :
exampleClass(T inVariable)
{
variable = inVariable;
}
int display()
{
std::ostringstream ss{};
ss << variable;
return ss.str().length();
}
};
Last edited on Apr 25, 2020 at 12:53am UTC