How to convert string into string?

closed account (Ey80oG1T)
So I have a template class which takes a value, and assuming that the value is a number, then it will turn it to a string, and count it's length.

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
template<typename dataType>
class squid
{
private:
	dataType variable;

public:

	squid(dataType inVariable)
	{
		variable = inVariable;
	}

	int display()
	{
		std::string set = std::to_string(variable);
		return set.length();
	}
};

int main()
{
	squid<double> number(5.55);
	std::cout << number.display();
}


Now this works fine, however, if I put in a string, then the entire code breaks down.

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
template<typename dataType>
class squid
{
private:
	dataType variable;

public:

	squid(dataType inVariable)
	{
		variable = inVariable;
	}

	int display()
	{
		std::string set = std::to_string(variable);
		return set.length();
	}
};

int main()
{
	squid<std::string> number("5.55");
	std::cout << number.display();
}


Apparently to_string() cannot convert a string to a string. Is there any way I can prevent this? How do I check if the user inputted a string?
Specialization?
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
36
37
38
#include <string>
#include <iostream>

template<typename dataType>
class squid
{
private:
	dataType variable;

public:

	squid(dataType inVariable)
	: variable(inVariable)
	{
	}

	int display()
	{
		std::string set = std::to_string(variable);
	    std::cout << set << '\n';
		return set.length();
	}
};

template <>
int squid<std::string>::display()
{
	return variable.length();
}


int main()
{
	squid<std::string> number("5.55");
	std::cout << number.display() << '\n';
	squid<double> text(5.55);
	std::cout << text.display() << '\n';
}

4
5.550000
8
Last edited on
Please don't double post.
Topic archived. No new replies allowed.