How to detect is template is a string

closed account (Ey80oG1T)
So I have this function:

1
2
3
4
5
6
template<typename T>
int display(T value)
{
  string set = to_string(value);
  return value.length();
}


But if I put a string as an argument, the code breaks down. So how do I counter this?
You can specialize the template to not call to_string when the argument is already a string.

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
// Example program
#include <iostream>
#include <string>

using std::string;

template <typename T>
int display(T value)
{
    using std::to_string;
    string set = to_string(value);
    return set.length();
}
template <>
int display(const char* c_str)
{
    return string(c_str).length(); // strlen
}
template <>
int display(string str)
{
    return str.length();   
}

int main()
{
    using std::cout;
    cout << display(42) << " ";
    cout << display("const char*") << " ";
    cout << display(string("hello world!")) << " ";
}

Someone else might have a more succinct solution.
closed account (Ey80oG1T)
Is there a way to put all those in one function? If not, could I do so with a class?
Probably could use constexpr if.
Perhaps this link might provide an answer?

https://stackoverflow.com/questions/14294267/class-template-for-numeric-types

Also don't forget other User Defined Types, or even the standard containers could be passed into your template function?

Also posted here: http://www.cplusplus.com/forum/general/269879/

Please don't crosspost.
Last edited on
Use a stringstream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <sstream>

template<typename T>
int display(T value)
{
  std::ostringstream ss{};
  ss << value;
  return ss.str().length();
}

int main()
{
    std::cout << display(453) << std::endl;
    std::cout << display(4.7632) << std::endl;
    std::cout << display('c') << std::endl;
    std::cout << display("asdfadsf") << std::endl;
    std::cout << display(std::string("STR")) << std::endl;

    return 0;
}
Last edited on
You could just do ss.str().length(), but yes I like that solution more. It makes it so that a << operator must be defined as opposed to a to_string function, which matches how streams are expected to work in most classes.
Last edited on
@Ganado, Yeah I noticed that right after I posted it. I have edited my code now.
Last edited on
Topic archived. No new replies allowed.