Lets assume, that I have a template function foo(T)
and I only want to accept integer types for T
. So the main.cpp
might look something like this:
int main()
{
int i = 1;
foo(i); // Should work fine
foo(&i); // Should not compile
}
Now, there are two options to achieve this, that I am aware of:
1) Using static_assert
#include <type_traits>
template<typename T> void foo(T value) {
static_assert(std::is_integral<T>::value, "Not integral!");
// Logic goes here
}
This option has the advantage, that I am able to specify an error message. The disadvantage is that my g++ 4.9.3 does produce a lot of error output for discrepancies among my type T
and my // Logic
.
2) Using std::enable_if
in template argument list
#include<type_traits>
template<typename T, class = typename std::enable_if<std::is_integral<T>::value>::type>
void foo(T value) {
// Logic goes here
}
The disadvantage is that the error output produced is not very descriptive of the problem, the advantage is that there is a lot less of it. (The amount of error output could be reduced by combining both approaches.)
Questions
For completeness, are there any other (good) ways of achieving the same result?
What option should take less compile time?
As far as I know, both approaches are equivalent in what types they allow in foo()
. Are they?
What I am asking is an expert opinion on "how should this be done in a good code" and what are the conditions of when to use what approach.
Thank you for any input.
Aucun commentaire:
Enregistrer un commentaire