Value type of the class of the class or the class itself
I am trying to create a class similar to the following
#include <cstdlib>
#include <iostream>
#include <typeinfo>
#include <type_traits>
#include <complex>
template<class K, class T = typename std::conditional<std::is_class<K>::value, typename K::value_type, K>::type>
class A {
public:
K v;
T u;
void type() {
std::cout << typeid(u).name() << std::endl;
}
};
int main() {
A<std::complex<double>> a;
a.type();
A<std::complex<float>> b;
b.type();
A<float> c;
c.type();
A<double> d;
d.type();
return 0;
}
So the output will be:
d
f
f
d
Otherwise, I need a u
type variable T
, if it K
has a type, std::complex<K>
or K
otherwise. Can this be done with C ++ 11? Thank.
source to share
You can use partial specialization to get the type you want, perhaps like this:
template <typename T, bool> struct ValueType
{
using type = T;
};
template <typename T> struct ValueType<T, true>
{
using type = typename T::value_type;
};
template <class K>
struct A
{
using T = typename ValueType<K, std::is_class<K>::value>::type;
void type()
{
std::cout << typeid(T).name() << std::endl;
}
};
If you need an appropriate data member, you can also alias the type to a class member and then declare the data member of the type T
.
source to share
You can easily use a private specialization and trait for this:
template <class T>
struct TypeForU_Class
{
typedef T type;
};
template <class T>
struct TypeForU_Class<std::complex<T>>
{
typedef T type;
};
template <class T>
using TypeForU = typename TypeForU_Class<T>::type;
template <class K, class T>
class A
{
public:
K v;
TypeForU<T> u;
// rest as before
};
source to share