template<class T>
class A
{};
I need something similar to std::is_same
or std::is_base
that should be true for e.g. std::xxxx<double, A<double>>::value
(since double is type used as template parameter) but false for std::xxxx<int, A<double>>::value
at compile time. How to do this?
You can do the following:
#include <type_traits>
template<typename Type, typename Template>
struct is_template_param : std::false_type {};
template<typename Type, template<typename...> class Template, typename... R>
struct is_template_param<Type, Template<Type, R...>> : std::true_type {};
template<typename T>
struct TestStruct1 {};
template<typename T1, typename T2 = float>
struct TestStruct2 {};
static_assert(is_template_param<int, TestStruct1<int>>::value, "");
static_assert(!is_template_param<int, TestStruct2<double>>::value, "");
static_assert(is_template_param<int, std::vector<int>>::value, "");
Edit:
And here's more generic version, which allows you to check if a type is the N-th template parameter of some template:
#include <type_traits>
#include <tuple>
template<std::size_t N, typename Type, typename Template>
struct is_nth_template_param : std::false_type {};
template<std::size_t N, typename Type, template<typename...> class Template, typename... TplParams>
struct is_nth_template_param<N, Type, Template<TplParams...>> : std::is_same<Type, std::tuple_element_t<N, std::tuple<TplParams...>>> {};
// is_template_param from the first version could be replaced with this:
template<typename Type, typename Template>
using is_1st_template_param = is_nth_template_param<0, Type, Template>;
It is possible to write a dedicate trait:
#include <type_traits>
template<typename T, typename TA> struct
has_parameter: public ::std::false_type
{};
template<typename T> struct
has_parameter<T, A<T>>: public ::std::true_type
{};
template<typename T, typename TA>
constexpr bool const has_parameter_v = has_parameter<T, TA>::value;
static_assert(has_parameter_v<double, A<double>>);
static_assert(!has_parameter_v<int, A<double>>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With