Is there a way to check which data type the programmer chose when they create an object using your template?

Let's say I made a class that uses a template. When the programmer creates an object using my class they have to decide which data type to use, just like when you create a vector or set. When I write my class, is it possible to check which data type the programmer chose inside one of my functions or constructors?

I know it's probably not a good idea for your function to do different things depending on if the programmer is using strings or doubles. I am just wondering if it is possible to do something like this inside one of the class functions or constructors:

1
2
3
4
5
6
  if(data type == std::string){
     //do this
}
  if(data type == double){
    //do this instead
}
Yes, it's possible.

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

template <typename T>
void foo(T param)
{
    if (std::is_same<T, std::string>::value)
        std::cout << "You passed in a string." << std::endl;
    else if (std::is_same<T, double>::value)
        std::cout << "You passed in a double." << std::endl;
    else
        std::cout << "You passed in a type I don't care about." << std::endl;
}

int main()
{
    std::string a;
    double b;
    float c;
    
    foo(a);
    foo(b);
    foo(c);
}

You passed in a string.
You passed in a double.
You passed in a type I don't care about.

https://stackoverflow.com/questions/6251889/type-condition-in-template
I suggest reading Xeo's post for alternatives, though.
Last edited on
There is "template specialisation" in which you explicitly write code for a particular type having been used as the templated parameter. Here are some words - https://www.cprogramming.com/tutorial/template_specialization.html - but now that you know what it's called, you can do your own research.

It's also possible to use Run Time Type Identification, and also make use of the typeid function or std::is_same (and probably others I'm not aware of), to branch depending on a specific type.

As you suspect, it's generally a bad sign and when I find myself considering it, I go back and re-examine my design.
Last edited on
Topic archived. No new replies allowed.