Answer the question
In order to leave comments, you need to log in
How to disable function definition through templates?
There is a class:
template<const std::size_t rows, const std::size_t columns>
class Matrix
{
...
}
int GetDeterminant() const noexcept
template<const std::size_t T, const std::size_t U>
struct are_values_equal
{
constexpr static bool value = T == U;
};
template<typename std::enable_if<are_values_equal<rows, columns>::value>::type = true>
Answer the question
In order to leave comments, you need to log in
It's not as important to simply enable or disable a method based on type template arguments as it is important to explain to the user of the type why a method is available there and not here.
First of all, it is worth understanding SFINAE , because it is this mechanism that allows you to "turn off" definitions in the code under special conditions.
Template inference failure should not result in a code translation error. This is a delicate mechanism that always balances on the edge between translation and error. When you want to turn off the definition of a function, you always need to provide an alternative for it under different conditions.
In this regard, it is very important to separate the template output of the matrix itself and the template output of the matrix methods.
It is the attempts to derive matrix method templates that should fail. In the most literal sense, the method will turn off for a non-square matrix because it could not be deduced from the template.
template< size_t ROWS, size_t COLUMNS >
struct Matrix final
{
template< size_t R = ROWS, size_t C = COLUMNS >
inline std::enable_if_t<R == C, int> GetDeterminant() const
{
return 0;
}
};
GetDeterminant
it was not possible to withdraw from the template? There will be a translation error saying that the method was not found. It doesn't tell the user anything. This simply instructs the translator to stop broadcasting. The user, especially if he is not tempted to know about SFINAE, will not be able to understand the cause of the translation error. Such a situation creates the risk of wasting time investigating the causes of the error. template< size_t ROWS, size_t COLUMNS >
struct Matrix final
{
template< size_t R = ROWS, size_t C = COLUMNS >
inline std::enable_if_t<R != C, int> GetDeterminant() const = delete;
template< size_t R = ROWS, size_t C = COLUMNS >
inline std::enable_if_t<R == C, int> GetDeterminant() const
{
return 0;
}
};
GetDeterminant
. template< size_t ROWS, size_t COLUMNS >
struct Matrix final
{
inline int GetDeterminant() const
{
static_assert( ROWS == COLUMNS, "Matrix should be square to calculate the determinant." );
return 0;
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question