2 c++ templates types class-template c++17
I wanted to know if a variable can be equal to a type (here it's the magic_type)
#include <typeinfo>
template<typename T>
class C
{
public:
magic_type t;
t list;
T data;
C(void)
{
if (typeid(data) == typeid(int))
t = float; // so typeid(list) = typedid(float)
else
t = int; // and typeid(list) = typedid(int)
}
};
Run Code Online (Sandbox Code Playgroud)
If you want the magic_type be float when T == int and otherwise float, use std::conditional_t. This will resolve the magic_type at compile time.
In order to check whether two types are the same, you could use std::is_same_v. Include <type_traits>, for both of the trait's usage.
#include <type_traits> // std::conditional_t, std::is_same_v
template<typename T>
class C
{
// type alias
using magic_type = std::conditional_t<std::is_same_v<T, int>, float, int>;
magic_type t; // now `magic_type` == `float` if `T` == `int`, otherwise `float`
T data;
public:
// ... code
};
Run Code Online (Sandbox Code Playgroud)