Domanda

Il codice seguente è OK:

template <class T>
std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }

template <class T>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }

int main(void){
  foo(1);  // return true
  auto std::vector<int> a{2};
  foo(a);  // return false
}

Ma quando uso una classe per raggrupparli, non può essere compilato:

template <class T>
class test {
public:

std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }

std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
};

int main(...) {
  test<int> obj;
  obj.foo(1);
  test<std::vector<int>> obj2;
  std::vector<int> tmp{2};
  obj2.foo(tmp);
}

Stampa clang ++:

error: functions that differ only in their return type cannot be overloaded

Quindi scrivo qualcosa da imbrogliare al compilatore (aggiungi una S in secondo foo):

template <class S>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }

Non può ancora funzionare:

error: no type named 'type' in 'std::enable_if<false, bool>'

Come posso farlo funzionare in una classe?

È stato utile?

Soluzione 2

Entrambe le funzioni dei membri dovrebbero avere un parametro modello diverso (i seguenti funzionerà OK)

template <class T>
class test {
public:

template<typename U>
typename std::enable_if<std::is_atomic<U>::value, bool>::type
foo(U t) { return true; }

template<typename U>
typename std::enable_if<tmp::is_sequence<U>::value, bool>::type
foo(U t) { return false; }

};

Altri suggerimenti

Hai dimenticato di aggiungere ::genere dopo abilita_if: (vedere abilita_if)

template <class T> std::enable_if<std::is_atomic<T>::value, bool>::type
foo(T t) { return true; }

Se vuoi davvero fare quello che stai facendo, il linguaggio classico è introdurre un argomento di Sfinae falso con un valore predefinito:

bool foo(T t, std::enable_if<..., void*> = nullptr) { ... }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top