Reputation: 799
I'm implementing a TypeInfo class with a IsNothrowMoveConstructible property. I would like to set this parameter to true if the move constructor of the type T is marked with noexcept. Referencing the default constructor by noexcept(noexcept(T())) seems to work, however I didn't figure out yet how to reference the move constructor. I guess the solution will be something like this:
template <typename T>
struct TypeInfo
{
enum
{
...
IsNothrowMoveConstructible = noexcept(noexcept(T(T&&))),
...
};
};
I know, that I can use std::is_nothrow_move_constructible, but my goal is to find out how to use noexcept() operator in such a situation.
Upvotes: 1
Views: 135
Reputation: 73406
The operator noexcept()
needs a true expression. Unfortunately T(T&&)
is not a valid expression.
So you'd need to instantiate an occurrence of T
and use std::move()
to make sure it uses the move constructor if there's one. Here a proof of concept:
template <typename T>
struct TypeInfo
{
bool test()
{
T t;
bool IsNothrowMoveConstructible = noexcept(T(std::move(t)));
return IsNothrowMoveConstructible;
};
};
The problem is that this becomes much more error prone. If T has no default constructor, it will fail to compile. Same if move constructor was implicitly or explicitly deleted.
But if you can live with these flaws, as the value is determined at compile time and is therefore constant, you could use a T member and define a constant in an enum:
struct TypeInfo
{
T t;
enum {
IsNothrowMoveConstructible = noexcept(T(std::move(t)))
};
};
Here an online demo.
Upvotes: 1