Mixing template specialisation and enable_if in a function template with only a templated return type
-
05-02-2021 - |
Question
I have the following code that fails to compile on VC2010:
#include <type_traits>
using namespace std;
template <class C>
typename enable_if<true, C>::type
foo()
{ return C(); }
template <>
bool
foo()
{ return true; } // error C2785: 'enable_if<true,_Type>::type foo(void)'
// and 'bool foo(void)' have different return types
int main()
{
auto a = foo<int>();
auto b = foo<bool>();
}
The error message seems erroneous, as the first version of foo()
seems functionally identical to template <class C> C foo();
which happily compiles.
Is there a way to mix-and-match enable-if'd function templates and explicit template specialisations?
Solution
A function template specialization is (thankfully!) not required to return the same type as the non-specialized template, so this is not the issue here.
In fact, enable_if
has nothing to do with your error, your code is simply missing the template arguments list in the specialization:
template <>
bool foo<bool>()
{ return true; }
On a sidenote, why are you using enable_if
if the condition is always true? (I guess this is not the case in your real code, but I just want to be sure :)!)
OTHER TIPS
The problem is just the syntax of the full specialization. It should be:
template <> bool foo<bool>() { return true; }
^^^^^^