constexpr check of a type - c++

I'm trying to overload some function based on whether or not I'm passing an Eigen matrix to them, and I wanted to make myself some nice constexpr function to improve readability.
For that I decided to emulate the implementation of std::is_same given on https://en.cppreference.com/w/cpp/types/is_same
template<class T, class U>
struct is_same : std::false_type {};
template<class T>
struct is_same<T, T> : std::true_type {};
And I told myself sure, easy enough:
template <typename T>
bool constexpr is_eigen() { return false; }
template <typename T, typename Eigen::Matrix<typename T::Scalar,
T::RowsAtCompileTime,
T::ColsAtCompileTime,
T::Options,
T::MaxRowsAtCompileTime,
T::MaxColsAtCompileTime>>
bool constexpr is_eigen() { return true; }
However my Eigen types resolve to the first template specialization, not the first (putting a dummy typename U doesn't help).
I also tried something like:
template <typename T, bool is_it = std::is_same<T,
Eigen::Matrix<typename T::Scalar,
T::RowsAtCompileTime,
T::ColsAtCompileTime,
T::Options,
T::MaxRowsAtCompileTime,
T::MaxColsAtCompileTime>>::value>
bool constexpr is_eigen() { return is_it; }
template <typename T, typename = std::enable_if_t<!std::is_class<T>::value>>
bool constexpr is_eigen() { return false; }
But for non-Eigen classes the first overload doesn't resolve, and trying anything to change that means Eigen will still hit the false branch
Basically, any default branch I come up with gets taken even for Eigen-types. I hate SFINAE :(

You can use partial specialization to match a Eigen::Matrix<...> like so
template <typename T>
struct is_eigen_impl : std::false_type {};
template <typename T, int... Is>
struct is_eigen_impl<Eigen::Matrix<T, Is...>> : std::true_type {};
template <typename T>
constexpr bool is_eigen = is_eigen_impl<T>::value;

If I understand correctly, you trying to obtain something as follows (caution: code not tested)
template <typename T>
constexpr std::false_type is_eigen_helper (T const &);
template <typename T, int ... Is>
constexpr std::true_type is_eigen_helper (Eigen::Matrix<T, Is...> const &);
template <typename T>
constexpr auto is_eigen { decltype(is_eigen_helper(std::declval<T>()))::value };
In this case is_eigen<T> is a template variable, so is required C++14.
In C++11 you can define is_eigen<T> as a type
template <typename T>
using is_eigen = decltype(is_eigen_helper(std::declval<T>()));
so you can use is_eigen<T>::value to check if T is an Eigen::Matrix.
p.s.: template specialization, as in super's answer, is another (maybe better) way to do almost the same thing.
But, as pointed by Jarod42, there is a difference.
With my solution you obtain that is_eigen<T> (or is_eigen<T>::value, in C++11) is true when T is a Eigen::Matrix of some type or a class that inherits from some Eigen::Matrix class.
With super's solution you get that is_eigen<T>::value is true only if T is an Eigen::Matrix. When T inherit from an Eigen::Matrix, is_eigen<T> is false.
See you what is better for your needs.

Related

Check whether a default-deleted function template is explicitly specialized for a specific type?

(This question has been significantly edited, sorry.)
Suppose I have several non-constexpr function templates, which default to being deleted:
template <typename T> void foo() = delete;
template <typename T> int bar(int x) = delete;
// etc.
and have some explicit specialization as an exception to the general-case deletion.
I want to write code (e.g. a trait class?) which, given the identifier of one of these functions and a type T, detects, at compile-time, whether the specified function is explicitly specialized for type T. The code needs to be generic, i.e. not a separate detector for each of the functions.
Notes:
Looking for a C++11 solution.
We may assume the specified function is deleted by default - if that helps.
Ideally, it would like like instantiation_exists<decltype(foo), foo, int>::value or instantiation_exists<int>(foo, tag<int>) or instantiation_exists(foo, tag<int>) or something along those lines.
Edit: #Jarod42's wrote up an SFINAE example in a comment on an earlier version of this question, which was about a per-single-function detector. I tried to generalize/genericize it using a template-template parameter:
#include <type_traits>
template <typename T> void foo() = delete;
template <> void foo<int>() {}
template <template<typename U> typename F, typename T, typename = decltype(F<T>()) >
std::true_type test(int);
template <template<typename U> typename F, typename T>
std::false_type test(...);
template <typename T>
using foo_is_defined = decltype(test<foo<T>, T>(0));
static_assert(foo_is_defined<int>::value);
static_assert(not foo_is_defined<int*>::value);
but that was a wash (Coliru).
We cannot pass template function, or overloads in template parameter.
We can turn those function in functor:
template <typename T>
struct identity_type
{
using type = T;
};
template <typename F, typename T, typename = decltype(std::declval<F>()(identity_type<T>{})) >
std::true_type test(int);
template <typename F, typename T>
std::false_type test(...);
auto foos = [](auto tag, auto&&... args)
-> decltype(foo<typename decltype(tag)::type>((decltype(args))(args)...))
{
return foo<typename decltype(tag)::type>((decltype(args))(args)...);
};
template <typename T>
using is_foo = decltype(test<decltype(foos), T>(0));
Demo
I use generic lambda, so C++14.
in C++11, it would be really verbose:
struct foos
{
template <typename T, typename... Ts>
auto operator()(identity_type<T>, Ts&&... args) const
-> decltype(foo<T>(std::forward<Ts>(args)...))
{
return foo<T>(std::forward<Ts>(args)...);
};
};

Disable class specialization using concepts

I'm implementing my own version of std::span using Concepts TS. I got stuck implementing these constructors:
template<class Container> constexpr span(Container& cont);
template<class Container> constexpr span(const Container& cont);
Remarks: These constructors shall not participate in overload resolution unless:
Container is not a specialization of span, and
Container is not a specialization of array
How to implement this using concepts?
First, create a trait to check for specializations. array and span look the same in the sense that they take a type parameter and a non-type parameter:
template <typename T, template <typename, auto> class Z>
struct is_specialization : std::false_type { };
template <typename A, auto V, template <typename, auto> class Z>
struct is_specialization<Z<A,V>, Z> : std::true_type { };
template <typename T, template <typename, auto> class Z>
inline constexpr bool is_specialization_v = is_specialization<T, Z>::value;
And then we can build up a concept from that:
// the last bullet point
template <typename T, typename E>
concept ValidForElement =
ConvertibleTo<std::remove_pointer_t<T>(*)[], E(*)[]>;
template <typename T, typename E>
concept AllowedContainer =
// not a specialization of span (note: requires forward declaration of span)
!is_specialization_v<std::remove_cv_t<T>, std::span>
// not a specialization of array
&& !is_specialization_v<std::remove_cv_t<T>, std::array>
// not a raw array
&& !std::is_array_v<std::remove_cv_t<T>>
&& requires (T cont) {
// data(cont) is well-formed and has a valid type
{ data(cont); } -> ValidForElement<E>
// size(cont) is well-formed
{ size(cont); }
};
Which you would use like:
template <typename Element, std::ptrdiff_t Extent = -1>
struct span {
template <typename C> requires AllowedContainer<C, Element>
span(C&);
template <typename C> requires AllowedContainer<C const, Element>
span(C const&);
};
The const-ness requirement there prevents the nice partial-concept-id syntax, but we could just add another concept for that I guess:
template <typename T, typename E>
concept ConstAllowedContainer = AllowedContainer<T const, E>;
template <typename Element, std::ptrdiff_t Extent = -1>
struct span {
template <AllowedContainer<E> C> span(C&);
template <ConstAllowedContainer<E> C> span(C const&);
};
Not sure if there's a cleverer approach here yet.
But really this whole pair-of-constructor thing is probably a mistake and you want to do a forwarding reference:
template <typename Element, std::ptrdiff_t Extent = -1>
struct span {
template <AllowedContainer<E> C>
span(C&&);
};
This last approach requires a few tweaks to the concept (all the remove_cv_t's should become remove_cvref_t's).
You can use type traits to check whether some type is a specialization of span or std::array. This works for me:
#include <type_traits>
template<typename, std::ptrdiff_t> class span;
template <typename T>
struct is_array : std::false_type { };
template <typename T, size_t N>
struct is_array<std::array<T, N>> : std::true_type { };
template <typename T>
struct is_span : std::false_type { };
template <typename T, std::ptrdiff_t P>
struct is_span<span<T, P>> : std::true_type { };
template <typename T>
concept bool NotSpanNotArray = !is_array<T>::value && !is_span<T>::value;
template<typename, std::ptrdiff_t> class span {
public:
template<NotSpanNotArray T> constexpr span(T& cont);
// template<NotSpanNotArray T> constexpr span(const T& cont);
};
Working demo: https://wandbox.org/permlink/M0n60U8Hl4mpacuI
Just I am not 100% sure whether such a solution meets that participate in overload resolution if and only if requirement. Some language-lawyer might clarify this.
UPDATE
I just realized that std::is_array works only for "ordinary" arrays, not std::array. Therefore I added a custom is_array type trait as well.
You are miss-using concepts. In a concept world span constructor will look like this with the concept-ts syntax:
struct span{
span(const ContiguousRange&);
span(ContiguousRange&);
span(const span&) =default;
span(span&) =default;
};
or with c++20:
struct span{
span(const ContiguousRange auto&);
span(ContiguousRange auto&);
span(const span&) =default;
span(span&) =default;
};
Concepts are here to ease abstraction. So that if your interface get more complex when using concepts then you have missed the abstraction. The abstraction here is ContiguousRange (thanks to #Lyberta).

Q: Template class that takes either a normal type or a template template argument

Recently I designed meta-types and the possible operations that would allow compile-time type concatenations:
#include <tuple>
template<template<typename...> typename T>
struct MetaTypeTag
{};
/*variable template helper*/
template<template<typename...> typename T>
constexpr MetaTypeTag<T> meta_type_tag = {};
template<typename T>
struct TypeTag
{};
/*comparison*/
template<typename T>
constexpr bool operator==(TypeTag<T>, TypeTag<T>) { return true; }
template<typename T, typename U>
constexpr bool operator==(TypeTag<T>, TypeTag<U>) { return false; }
/*variable template helper*/
template<typename T>
constexpr TypeTag<T> type_tag = {};
template<template<typename...> typename T, typename... Ts>
constexpr TypeTag<T<Ts...>> combine(MetaTypeTag<T>, TypeTag<Ts>...)
{
return {};
}
int main()
{
constexpr auto combined_tag = combine(meta_type_tag<std::tuple>, type_tag<int>, type_tag<float>);
static_assert(combined_tag == type_tag<std::tuple<int, float>>, "");
}
The std::tuple without template arguments cannot be used as a type, but may still appear in the template template parameter.
Now if we try to go one step further, the question is whether there is any way to unify struct MetaTypeTag and struct TypeTag, since they are both empty classes with one template parameter, or at least it could be possible to use the same variable template type_tag but redirect to a different class depending on the type category? So I would imagine something like this:
template<???>
constexpr auto type_tag = ????{};
//use with 'incomplete type'
type_tag<std::tuple> //MetaTypeTag<std::tuple>
//use with regular type
type_tag<int> //TypeTag<int>
I tried all possible ways - redefinition, explicit specialization, partial specialization, optional template parameters, conditional using alias, but none worked. I had hoped C++17's template<auto> would help, but it turns out that one is for non-type only.
the question is whether there is any way to unify struct MetaTypeTag and struct TypeTag, since they are both empty classes with one template parameter
I don't thinks so.
The best I can imagine to simplify a little (very a little) your code is define a couple of overloaded constexpr function, say getTag()
template <typename T>
auto constexpr getTag ()
{ return TypeTag<T>{}; }
template <template <typename ...> typename T>
auto constexpr getTag ()
{ return MetaTypeTag<T>{}; }
so you can call getTag<T>() where T is either a type or a template.
So you can call combine() as follows
constexpr auto combined_tag
= combine(getTag<std::tuple>(), getTag<int>(), getTag<float>());
But I don't think is a great improvement.

How can I get the index of a type in a variadic class template?

I have a variadic Engine template class:
template <typename ... Components> class Engine;
I'd like to assign a number to each component at compile time which is equivalent to their ordering. This would be returned when making the following call:
template <typename Component> int ordinal();
So for example if:
Engine<PositionComponent, PhysicsComponent, InputComponent> engine;
was declared, the call:
engine.ordinal<PhysicsComponent>();
would return 1 and a similar call with InputComponent instead of PhysicsComponent would return 2.
Is it possible, and if yes, how would one go about it?
In Boost.Mp11, this is a short one-liner (as always):
template <typename... Components>
struct Engine {
template <typename Component>
static constexpr int ordinal() {
return mp_find<Engine, Component>::value;
}
};
Note that if Component is absent, this will return sizeof...(Components). If desired, you can add a static assertion to verify this.
My original answer follows below the fold...
So you want to find the index of Component in Components...?
template <typename... >
struct index;
// found it
template <typename T, typename... R>
struct index<T, T, R...>
: std::integral_constant<size_t, 0>
{ };
// still looking
template <typename T, typename F, typename... R>
struct index<T, F, R...>
: std::integral_constant<size_t, 1 + index<T,R...>::value>
{ };
Usage:
template <typename Component>
size_t ordinal() { return index<Component, Components...>::value; }
As constructed, trying to get the ordinal of a Component not in Components... will be a compile error. Which seems appropriate.
My goal below is to keep things in the compile-time realm as much as possible.
This is an alias to remove some boilerplate. std::integral_constant is a wonderful std type that stores a compile-time determined integer-type:
template<std::size_t I>
using size=std::integral_constant<std::size_t, I>;
Next, a index_of type, and an index_of_t that is slightly easier to use:
template<class...>struct types{using type=types;};
template<class T, class Types>struct index_of{};
template<class T, class...Ts>
struct index_of<T, types<T, Ts...>>:size<0>{};
template<class T, class T0, class...Ts>
struct index_of<T, types<T0, Ts...>>:size<
index_of<T,types<Ts...>>::value +1
>{};
This alias returns a pure std::integral_constant, instead of a type inheriting from it:
template<class T, class...Ts>
using index_of_t = size< index_of<T, types<Ts...>>::value >;
Finally our function:
template <class Component>
static constexpr index_of_t<Component, Components...>
ordinal() const {return{};}
it is not only constexpr, it returns a value that encodes its value in its type. size<?> has a constexpr operator size_t() as well as an operator(), so you can use it in most spots that expect integer types seamlessly.
You could also use:
template<class Component>
using ordinal = index_of_t<Component, Components...>;
and now ordinal<Component> is a type representing the index of the component, instead of a function.
I'm adding this for completeness sake, it utilizes C++11's constexpr functionality, and a few stl functions. I feel it is a little cleaner than the other solutions.
//Same type
template <typename Target,typename T,typename ...Rest>
constexpr typename std::enable_if<std::is_same<Target,T>::value, size_t>
_ordinal(){
return 0;
}
//Different types
template <typename Target,typename T,typename ...Rest>
constexpr typename std::enable_if<!std::is_same<Target,T>::value, size_t>
_ordinal(){
return 1+_ordinal<Target,Rest...>();
}
UNTESTED:
template <int, typename>
constexpr int index_of() { return -1; } // type not found
template <int N, typename Component, typename Cur, typename... Components>
constexpr int index_of() {
return std::is_same<Component, Cur>::value ? N : index_of<N+1, Component, Components...>();
}
template <typename... Components>
template <typename Component>
constexpr int engine<Components...>::ordinal() {
return index_of<0, Component, Components...>();
}
I could have used structs, but I find this much cleaner (without all the ::type ugliness).
If you want a compile-time error when the type is not found, change ordinal to:
template <typename... Components>
template <typename Component>
constexpr int engine<Components...>::ordinal() {
static_assert(index_of<0, Component, Components...>()!=-1, "invalid component");
return index_of<0, Component, Components...>();
}

Checking a member exists, possibly in a base class, C++11 version

In https://stackoverflow.com/a/1967183/134841, a solution is provided for statically checking whether a member exists, possibly in a subclass of a type:
template <typename Type>
class has_resize_method
{
class yes { char m;};
class no { yes m[2];};
struct BaseMixin
{
void resize(int){}
};
struct Base : public Type, public BaseMixin {};
template <typename T, T t> class Helper{};
template <typename U>
static no deduce(U*, Helper<void (BaseMixin::*)(), &U::foo>* = 0);
static yes deduce(...);
public:
static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0)));
};
However, it doesn't work on C++11 final classes, because it inherits from the class under test, which final prevents.
OTOH, this one:
template <typename C>
struct has_reserve_method {
private:
struct No {};
struct Yes { No no[2]; };
template <typename T, typename I, void(T::*)(I) > struct sfinae {};
template <typename T> static No check( ... );
template <typename T> static Yes check( sfinae<T,int, &T::reserve> * );
template <typename T> static Yes check( sfinae<T,size_t,&T::reserve> * );
public:
static const bool value = sizeof( check<C>(0) ) == sizeof( Yes ) ;
};
fails to find the reserve(int/size_t) method in baseclasses.
Is there an implementation of this metafunction that both finds reserved() in baseclasses of T and still works if T is final?
Actually, things got much easier in C++11 thanks to the decltype and late return bindings machinery.
Now, it's just simpler to use methods to test this:
// Culled by SFINAE if reserve does not exist or is not accessible
template <typename T>
constexpr auto has_reserve_method(T& t) -> decltype(t.reserve(0), bool()) {
return true;
}
// Used as fallback when SFINAE culls the template method
constexpr bool has_reserve_method(...) { return false; }
You can then use this in a class for example:
template <typename T, bool b>
struct Reserver {
static void apply(T& t, size_t n) { t.reserve(n); }
};
template <typename T>
struct Reserver <T, false> {
static void apply(T& t, size_t n) {}
};
And you use it so:
template <typename T>
bool reserve(T& t, size_t n) {
Reserver<T, has_reserve_method(t)>::apply(t, n);
return has_reserve_method(t);
}
Or you can choose a enable_if method:
template <typename T>
auto reserve(T& t, size_t n) -> typename std::enable_if<has_reserve_method(t), bool>::type {
t.reserve(n);
return true;
}
template <typename T>
auto reserve(T& t, size_t n) -> typename std::enable_if<not has_reserve_method(t), bool>::type {
return false;
}
Note that this switching things is actually not so easy. In general, it's much easier when just SFINAE exist -- and you just want to enable_if one method and not provide any fallback:
template <typename T>
auto reserve(T& t, size_t n) -> decltype(t.reserve(n), void()) {
t.reserve(n);
}
If substitution fails, this method is removed from the list of possible overloads.
Note: thanks to the semantics of , (the comma operator) you can chain multiple expressions in decltype and only the last actually decides the type. Handy to check multiple operations.
A version that also relies on decltype but not on passing arbitrary types to (...) [ which is in fact a non-issue anyway, see Johannes' comment ]:
template<typename> struct Void { typedef void type; };
template<typename T, typename Sfinae = void>
struct has_reserve: std::false_type {};
template<typename T>
struct has_reserve<
T
, typename Void<
decltype( std::declval<T&>().reserve(0) )
>::type
>: std::true_type {};
I'd like to point out according to this trait a type such as std::vector<int>& does support reserve: here expressions are inspected, not types. The question that this trait answers is "Given an lvalue lval for such a type T, is the expressions lval.reserve(0); well formed". Not identical to the question "Does this type or any of its base types has a reserve member declared".
On the other hand, arguably that's a feature! Remember that the new C++11 trait are of the style is_default_constructible, not has_default_constructor. The distinction is subtle but has merits. (Finding a better fitting name in the style of is_*ible left as an exercise.)
In any case you can still use a trait such as std::is_class to possibly achieve what you want.