Występuje problem dotyczący właściwego użycia funkcji enable_if i specjalizacji szablonu.Specjalizacje szablonów i problemy z włączonym_aktywnym interfejsem użytkownika
Po modyfikacji przykładu (ze względu na poufność), tutaj jest porównywalny przykład:
I have function called "less" that checks if 1st arg is less than 2nd arg. Let's say I want to have 2 different kinds of implementations depending on the type of input - 1 implementation for integer and another for double.
kod, który do tej pory wygląda to tak -
#include <type_traits>
#include <iostream>
template <class T,
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool less(T a, T b) {
// ....
}
template <class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool less(T a, T b) {
// ....
}
int main() {
float a;
float b;
less(a,b);
return 0;
}
Powyższy kod nie skompilować ponieważ - Mówi, że redefiniuję mniej metody.
Błędy są:
Z.cpp:15:19: error: template parameter redefines default argument
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
Z.cpp:9:19: note: previous default template argument defined here
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
^
Z.cpp:16:11: error: redefinition of 'less'
bool less(T a, T b) {
^
Z.cpp:10:11: note: previous definition is here
bool less(T a, T b) {
^
Z.cpp:23:5: error: no matching function for call to 'less'
less(a,b);
^~~~
Z.cpp:15:43: note: candidate template ignored: disabled by 'enable_if'
[with T = float]
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
3 errors generated.
Czy ktoś może wskazać, co jest błędem tutaj?
zasadniczo nie używasz 'enable_if' poprawnie z powodu sposobu wywołania typu zwracanego. – Alex
Szybkie rozwiązanie polega na dodaniu parametru "..." elipsy do jednego z szablonów, aby były uważane za wyraźne przeciążenia. – 0x499602D2
Lub zmień podpis (y) na 'szablon :: value> :: type * = nullptr>' –
vsoftco