I realize this is a pretty basic question, but I just want to confirm that I'm using std::enable_if
correctly because I'm a little uncertain what the "correct" error messages should be when attempting to call a disabled function.
Consider the following program (link), which is expected to not compile:
#include <type_traits>
template <int Z=0> std::enable_if_t<Z> function () { }
int main () {
function();
}
The error messages that GCC 9 outputs in C++17 mode are:
g++ --std=c++17 -W -Wall -pedantic smelly_template.cpp -o build-c++17/smelly_template
smelly_template.cpp: In function ‘int main()’:
smelly_template.cpp:6:12: error: no matching function for call to ‘function()’
6 | function();
| ^
smelly_template.cpp:3:40: note: candidate: ‘template<int Z> std::enable_if_t<(Z != 0)> function()’
3 | template <int Z=0> std::enable_if_t<Z> function () { }
| ^~~~~~~~
smelly_template.cpp:3:40: note: template argument deduction/substitution failed:
In file included from smelly_template.cpp:1:
/usr/include/c++/9/type_traits: In substitution of ‘template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type [with bool _Cond = (0 != 0); _Tp = void]’:
smelly_template.cpp:3:40: required by substitution of ‘template<int Z> std::enable_if_t<(Z != 0)> function() [with int Z = 0]’
smelly_template.cpp:6:12: required from here
/usr/include/c++/9/type_traits:2384:11: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
2384 | using enable_if_t = typename enable_if<_Cond, _Tp>::type;
| ^~~~~~~~~~~
My question is pretty simple: Are these the error message I should expect to see when using enable_if
correctly (e.g. are they just notes about what the compiler tried to do), or did I screw something up?
The reasons I am uncertain are:
- I was expecting the error output to only be "no matching function for call to 'function()'", and to stop there, as if I was calling a vanilla function that didn't exist. (I do not know where this expectation comes from, though.)
- In all the posts, tutorials, and documentation I've read concerning
enable_if
, every time somebody encounters the "no type named 'type' in enable_if" error, it always seems to be because they're doing something incorrectly (just on a cursory search: example, example, example, the list goes on).
So I'm wondering if I'm doing something incorrectly because I am also seeing the "no type named 'type'" error.
While it's true that I'm seeing the ultimate expected behavior -- compilation failure -- I'm more concerned right now about perfectly correct usage than simply meeting the program requirement (compilation failure) in some form.