I have a function that takes a template type to determine a return value. Is there any way to tell at compile time if the template type is some instantiation of a template c
Yet another improvement to the answer of @RichardHodges: Usually, one also wants to capture not only plain types, but rather all cv-qualified and ref-qualified types.
Put differently, if is_instance{}
is true, also is_instance{}
or is_instance{}
should be true. The current implementations in this thread don't support that.
The following code accounts for all cv-ref-qualified types, by adding another indirection and a std::decay_t
:
namespace
{
template typename>
struct is_instance_impl : public std::false_type {};
template typename U, typename...Ts>
struct is_instance_impl, U> : public std::true_type {};
}
template typename U>
using is_instance = is_instance_impl, U>;
Use it as
#include
template struct foo{};
template struct bar{};
int main()
{
std::cout << is_instance, foo>{} << std::endl; // prints 1
std::cout << is_instance const&, foo>{} < &&, foo>{} << std::endl; // prints 1
std::cout << is_instance &&, foo>{} << std::endl; // prints 0
}