With std::is_constructible
one can question some given type for the presence of a certain constructor:
struct A {};
struct B
{
explicit B(int, A, double) {}
};
int main()
{
std::cout<<std::is_constructible<B,int,A,double>::value<<std::endl; //prints true
}
Suppose one does not know type B
. Is there also a way to check whether there exists a constructor in B
which contains type A
, regardless of the other parameters? (--or, already sufficient, which contains type A
in the n-th position?)
Given a non-explicit
constructor, I figured out a workaround by using a type which can be implicitly converted to anything:
struct convert_to_anything
{
template<typename T>
operator T() const
{
return T{};
}
};
int main()
{
std::cout<<std::is_constructible<B, convert_to_anything, A, convert_to_anything>::value<<std::endl;
}
(Actually, and unexpected to me, I found empirically that it seems to work as well when explicit
is added to the constructor of B
... whereas I thought it would prevent from conversions?)
Still, with this workaround I would have to test all possible numbers of parameters. Say for an A
in the first position:
std::is_constructible<B, A>::value
|| std::is_constructible<B, A, convert_to_anything>::value
|| std::is_constructible<B, A, convert_to_anything, convert_to_anything>::value
//... and so on up to a chosen maximum size.
That seems a bit unsatisfying. Do you have any better workarounds?
Aucun commentaire:
Enregistrer un commentaire