Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a type is a type parameter for template class in C++?

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?

like image 982
Tony Avatar asked Jun 14 '18 20:06

Tony


2 Answers

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>;
like image 136
joe_chip Avatar answered Oct 05 '22 22:10

joe_chip


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>>);
like image 22
user7860670 Avatar answered Oct 05 '22 22:10

user7860670