Domanda

È possibile scrivere un modello che cambia comportamento a seconda che una determinata funzione membro sia definita su una classe?

Ecco un semplice esempio di ciò che vorrei scrivere:

template<class T>
std::string optionalToString(T* obj)
{
    if (FUNCTION_EXISTS(T->toString))
        return obj->toString();
    else
        return "toString not defined";
}

Quindi, se class T ha toString() definito, allora lo usa; altrimenti no. La parte magica che non so fare è la quot &; FUNCTION_EXISTS & Quot; parte.

È stato utile?

Soluzione

Sì, con SFINAE puoi verificare se una determinata classe fornisce un determinato metodo. Ecco il codice di lavoro:

#include <iostream>

struct Hello
{
    int helloworld() { return 0; }
};

struct Generic {};    

// SFINAE test
template <typename T>
class has_helloworld
{
    typedef char one;
    struct two { char x[2]; };

    template <typename C> static one test( typeof(&C::helloworld) ) ;
    template <typename C> static two test(...);    

public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

int main(int argc, char *argv[])
{
    std::cout << has_helloworld<Hello>::value << std::endl;
    std::cout << has_helloworld<Generic>::value << std::endl;
    return 0;
}

L'ho appena testato con Linux e gcc 4.1 / 4.3. Non so se sia portatile su altre piattaforme che eseguono compilatori diversi.

Altri suggerimenti

Questa domanda è vecchia, ma con C ++ 11 abbiamo un nuovo modo per verificare l'esistenza di funzioni (o l'esistenza di qualsiasi membro non di tipo, in realtà), basandosi nuovamente su SFINAE:

template<class T>
auto serialize_imp(std::ostream& os, T const& obj, int)
    -> decltype(os << obj, void())
{
  os << obj;
}

template<class T>
auto serialize_imp(std::ostream& os, T const& obj, long)
    -> decltype(obj.stream(os), void())
{
  obj.stream(os);
}

template<class T>
auto serialize(std::ostream& os, T const& obj)
    -> decltype(serialize_imp(os, obj, 0), void())
{
  serialize_imp(os, obj, 0);
}

Ora su alcune spiegazioni. Per prima cosa, utilizzo espressione SFINAE per escludere le funzioni serialize(_imp) dalla risoluzione del sovraccarico, se la prima espressione all'interno di decltype non è valida (ovvero, la funzione non esiste).

void() viene utilizzato per rendere il tipo di restituzione di tutte queste funzioni void.

L'argomento 0 viene utilizzato per preferire il os << obj sovraccarico se entrambi sono disponibili (letterale int è di tipo sfinae_true e come tale il primo sovraccarico è una corrispondenza migliore).


Ora, probabilmente vuoi che un tratto controlli se esiste una funzione. Fortunatamente, è facile scriverlo. Nota, tuttavia, che devi scrivere un tratto te stesso per ogni diverso nome di funzione che potresti desiderare.

#include <type_traits>

template<class>
struct sfinae_true : std::true_type{};

namespace detail{
  template<class T, class A0>
  static auto test_stream(int)
      -> sfinae_true<decltype(std::declval<T>().stream(std::declval<A0>()))>;
  template<class, class A0>
  static auto test_stream(long) -> std::false_type;
} // detail::

template<class T, class Arg>
struct has_stream : decltype(detail::test_stream<T, Arg>(0)){};

Esempio live.

E avanti alle spiegazioni. Innanzitutto, decltype(void(std::declval<T>().stream(a0)), std::true_type{}) è un tipo di supporto e sostanzialmente equivale a scrivere struct has_stream : decltype(...). Il vantaggio è semplicemente che è più corto.
Successivamente, std::true_type eredita da std::false_type o test_stream alla fine, a seconda che il std::declval check in sizeof fallisca o meno.
Infine, long ti dà un & Quot; valore & Quot; di qualunque tipo passi, senza che tu abbia bisogno di sapere come puoi costruirlo. Si noti che ciò è possibile solo in un contesto non valutato, come <=>, <=> e altri.


Nota che <=> non è necessariamente necessario, poiché <=> (e tutti i contesti non valutati) hanno ottenuto quel miglioramento. È solo che <=> offre già un tipo e come tale è solo più pulito. Ecco una <=> versione di uno dei sovraccarichi:

template<class T>
void serialize_imp(std::ostream& os, T const& obj, int,
    int(*)[sizeof((os << obj),0)] = 0)
{
  os << obj;
}

I parametri <=> e <=> sono ancora lì per lo stesso motivo. Il puntatore di array viene utilizzato per fornire un contesto in cui <=> può essere utilizzato.

Il C ++ consente di SFINAE utilizzare questo (notare che con C ++ 11 è presente è più semplice perché supporta SFINAE esteso su espressioni quasi arbitrarie - il seguito è stato progettato per funzionare con compilatori C ++ 03 comuni):

#define HAS_MEM_FUNC(func, name)                                        \
    template<typename T, typename Sign>                                 \
    struct name {                                                       \
        typedef char yes[1];                                            \
        typedef char no [2];                                            \
        template <typename U, U> struct type_check;                     \
        template <typename _1> static yes &chk(type_check<Sign, &_1::func > *); \
        template <typename   > static no  &chk(...);                    \
        static bool const value = sizeof(chk<T>(0)) == sizeof(yes);     \
    }

il modello e la macro sopra tentano di creare un'istanza di un modello, assegnandogli un tipo di puntatore della funzione membro e il puntatore della funzione membro effettiva. Se i tipi non si adattano, SFINAE fa ignorare il modello. Utilizzo come questo:

HAS_MEM_FUNC(toString, has_to_string);

template<typename T> void
doSomething() {
   if(has_to_string<T, std::string(T::*)()>::value) {
      ...
   } else {
      ...
   }
}

Ma nota che non puoi semplicemente chiamare quella funzione toString in quel ramo if. poiché il compilatore verificherà la validità in entrambi i rami, ciò fallirebbe nei casi in cui la funzione non esiste. Un modo è usare di nuovo SFINAE (enable_if può essere ottenuto anche da boost):

template<bool C, typename T = void>
struct enable_if {
  typedef T type;
};

template<typename T>
struct enable_if<false, T> { };

HAS_MEM_FUNC(toString, has_to_string);

template<typename T> 
typename enable_if<has_to_string<T, 
                   std::string(T::*)()>::value, std::string>::type
doSomething(T * t) {
   /* something when T has toString ... */
   return t->toString();
}

template<typename T> 
typename enable_if<!has_to_string<T, 
                   std::string(T::*)()>::value, std::string>::type
doSomething(T * t) {
   /* something when T doesnt have toString ... */
   return "T::toString() does not exist.";
}

Divertiti ad usarlo. Il vantaggio è che funziona anche per le funzioni membro sovraccaricate e anche per le funzioni membro const (ricordarsi di usare std::string(T::*)() const come tipo di puntatore della funzione membro allora!).

Sebbene questa domanda abbia due anni, oserò aggiungere la mia risposta. Spero che chiarisca la soluzione precedente, indiscutibilmente eccellente. Ho preso le risposte molto utili di Nicola Bonelli e Johannes Schaub e le ho unite in una soluzione che è, IMHO, più leggibile, chiara e non richiede l'estensione typeof:

template <class Type>
class TypeHasToString
{
    // This type won't compile if the second template parameter isn't of type T,
    // so I can put a function pointer type in the first parameter and the function
    // itself in the second thus checking that the function has a specific signature.
    template <typename T, T> struct TypeCheck;

    typedef char Yes;
    typedef long No;

    // A helper struct to hold the declaration of the function pointer.
    // Change it if the function signature changes.
    template <typename T> struct ToString
    {
        typedef void (T::*fptr)();
    };

    template <typename T> static Yes HasToString(TypeCheck< typename ToString<T>::fptr, &T::toString >*);
    template <typename T> static No  HasToString(...);

public:
    static bool const value = (sizeof(HasToString<Type>(0)) == sizeof(Yes));
};

L'ho controllato con gcc 4.1.2. Il merito va principalmente a Nicola Bonelli e Johannes Schaub, quindi dai loro un voto se la mia risposta ti aiuta :)

C ++ 20 - requires espressioni

Con C ++ 20 arrivano concetti e strumenti assortiti come optionalToString espressioni che sono un modo integrato per verificare l'esistenza di una funzione. Con tehm puoi riscrivere la tua funzione std::is_detected come segue:

template<class T>
std::string optionalToString(T* obj)
{
    constexpr bool has_toString = requires(const T& t) {
        t.toString();
    };

    if constexpr (has_toString)
        return obj->toString();
    else
        return "toString not defined";
}

Pre-C ++ 20 - Toolkit di rilevamento

N4502 propone un rilevamento preso per l'inclusione nella libreria standard C ++ 17 che può risolvere il problema in un modo un po 'elegante. Inoltre, è stato appena accettato nei fondamenti della libreria TS v2. Presenta alcune metafunzioni, tra cui if constexpr che possono essere utilizzate per scrivere facilmente il tipo o metafunzioni di rilevamento delle funzioni nella parte superiore di esso. Ecco come puoi usarlo:

template<typename T>
using toString_t = decltype( std::declval<T&>().toString() );

template<typename T>
constexpr bool has_toString = std::is_detected_v<toString_t, T>;

Si noti che l'esempio sopra non è testato. Il toolkit di rilevamento non è ancora disponibile nelle librerie standard ma la proposta contiene un'implementazione completa che puoi facilmente copiare se ne hai davvero bisogno. Funziona bene con la funzione C ++ 17 BOOST_TTI_HAS_MEMBER_FUNCTION:

template<class T>
std::string optionalToString(T* obj)
{
    if constexpr (has_toString<T>)
        return obj->toString();
    else
        return "toString not defined";
}

Boost.TTI

Un altro toolkit in qualche modo idiomatico per eseguire un tale controllo - anche se meno elegante - è Boost.TTI , introdotto in Boost 1.54.0. Per il tuo esempio, dovresti usare la macro bool. Ecco come puoi usarlo:

#include <boost/tti/has_member_function.hpp>

// Generate the metafunction
BOOST_TTI_HAS_MEMBER_FUNCTION(toString)

// Check whether T has a member function toString
// which takes no parameter and returns a std::string
constexpr bool foo = has_member_function_toString<T, std::string>::value;

Quindi, è possibile utilizzare has_member_function_toString per creare un controllo SFINAE.

Spiegazione

La macro value genera la metafunzione true che accetta il tipo selezionato come primo parametro del modello. Il secondo parametro del modello corrisponde al tipo restituito della funzione membro e i seguenti parametri corrispondono ai tipi dei parametri della funzione. Il membro T contiene std::string toString() se la classe has_member_function_toString<T, std::string>::value ha una funzione membro has_member_function_toString<std::string T::* ()>::value.

In alternativa, <=> può prendere un puntatore a funzione membro come parametro modello. Pertanto, è possibile sostituire <=> con <=>.

Una soluzione semplice per C ++ 11:

template<class T>
auto optionalToString(T* obj)
 -> decltype(  obj->toString()  )
{
    return     obj->toString();
}
auto optionalToString(...) -> string
{
    return "toString not defined";
}

Aggiornamento, 3 anni dopo: (e questo non è testato). Per verificare l'esistenza, penso che funzionerà:

template<class T>
constexpr auto test_has_toString_method(T* obj)
 -> decltype(  obj->toString() , std::true_type{} )
{
    return     obj->toString();
}
constexpr auto test_has_toString_method(...) -> std::false_type
{
    return "toString not defined";
}

Ecco a cosa servono i tratti del tipo. Sfortunatamente, devono essere definiti manualmente. Nel tuo caso, immagina quanto segue:

template <typename T>
struct response_trait {
    static bool const has_tostring = false;
};

template <>
struct response_trait<your_type_with_tostring> {
    static bool const has_tostring = true;
}

Bene, questa domanda ha già un lungo elenco di risposte, ma vorrei sottolineare il commento di Morwenn: esiste una proposta per C ++ 17 che la rende davvero molto più semplice. Vedi N4502 per i dettagli, ma come esempio autonomo considerare quanto segue.

Questa parte è la parte costante, inseriscila in un'intestazione.

// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf.
template <typename...>
using void_t = void;

// Primary template handles all types not supporting the operation.
template <typename, template <typename> class, typename = void_t<>>
struct detect : std::false_type {};

// Specialization recognizes/validates only types supporting the archetype.
template <typename T, template <typename> class Op>
struct detect<T, Op, void_t<Op<T>>> : std::true_type {};

poi c'è la parte variabile, in cui si specifica ciò che si sta cercando (un tipo, un tipo di membro, una funzione, una funzione membro ecc.). Nel caso del PO:

template <typename T>
using toString_t = decltype(std::declval<T>().toString());

template <typename T>
using has_toString = detect<T, toString_t>;

Il seguente esempio, tratto da N4502 , mostra una sonda più elaborata:

// Archetypal expression for assignment operation.
template <typename T>
using assign_t = decltype(std::declval<T&>() = std::declval<T const &>())

// Trait corresponding to that archetype.
template <typename T>
using is_assignable = detect<T, assign_t>;

Rispetto alle altre implementazioni sopra descritte, questa è abbastanza semplice: è sufficiente un set ridotto di strumenti (void_t e detect), non sono necessarie macro pelose. Inoltre, è stato segnalato (vedi N4502 ) che è misurabilmente più efficiente (tempo di compilazione e consumo di memoria del compilatore) rispetto agli approcci precedenti.

Ecco un esempio live . Funziona bene con Clang, ma sfortunatamente, le versioni GCC precedenti alla 5.1 hanno seguito una diversa interpretazione dello standard C ++ 11 che ha fatto sì che <=> non funzionasse come previsto. Yakk ha già fornito la soluzione: usa la seguente definizione di <=> ( void_t nell'elenco parametri funziona ma non come tipo restituito ):

#if __GNUC__ < 5 && ! defined __clang__
// https://stackoverflow.com/a/28967049/1353549
template <typename...>
struct voider
{
  using type = void;
};
template <typename...Ts>
using void_t = typename voider<Ts...>::type;
#else
template <typename...>
using void_t = void;
#endif

Questa è una soluzione C ++ 11 per il problema generale se " Se avessi fatto X, sarebbe compilato? "

template<class> struct type_sink { typedef void type; }; // consumes a type, and makes it `void`
template<class T> using type_sink_t = typename type_sink<T>::type;
template<class T, class=void> struct has_to_string : std::false_type {}; \
template<class T> struct has_to_string<
  T,
  type_sink_t< decltype( std::declval<T>().toString() ) >
>: std::true_type {};

Tratto has_to_string tale che has_to_string<T>::value è true se e solo se T ha un metodo .toString che può essere invocato con 0 argomenti in questo contesto.

Successivamente, userò il dispacciamento dei tag:

namespace details {
  template<class T>
  std::string optionalToString_helper(T* obj, std::true_type /*has_to_string*/) {
    return obj->toString();
  }
  template<class T>
  std::string optionalToString_helper(T* obj, std::false_type /*has_to_string*/) {
    return "toString not defined";
  }
}
template<class T>
std::string optionalToString(T* obj) {
  return details::optionalToString_helper( obj, has_to_string<T>{} );
}

che tende ad essere più gestibile delle espressioni SFINAE complesse.

Puoi scrivere questi tratti con una macro se ti ritrovi a farlo molto, ma sono relativamente semplici (poche righe ciascuno) quindi forse non ne vale la pena:

#define MAKE_CODE_TRAIT( TRAIT_NAME, ... ) \
template<class T, class=void> struct TRAIT_NAME : std::false_type {}; \
template<class T> struct TRAIT_NAME< T, type_sink_t< decltype( __VA_ARGS__ ) > >: std::true_type {};

ciò che fa sopra è creare una macro MAKE_CODE_TRAIT. Gli passi il nome del tratto desiderato e un codice che può testare il tipo <=>. Così:

MAKE_CODE_TRAIT( has_to_string, std::declval<T>().toString() )

crea la classe dei tratti sopra.

A parte questo, la tecnica di cui sopra fa parte di ciò che MS chiama " espressione SFINAE " e il loro compilatore del 2013 fallisce abbastanza duramente.

Si noti che in C ++ 1y è possibile la seguente sintassi:

template<class T>
std::string optionalToString(T* obj) {
  return compiled_if< has_to_string >(*obj, [&](auto&& obj) {
    return obj.toString();
  }) *compiled_else ([&]{ 
    return "toString not defined";
  });
}

che è un ramo condizionale della compilazione in linea che abusa di molte funzionalità C ++. Farlo probabilmente non ne vale la pena, in quanto il vantaggio (del codice in linea) non vale il costo (di quasi nessuno capisce come funziona), ma l'esistenza di tale soluzione potrebbe essere interessante.

Ecco alcuni snippet di utilizzo: * Le viscere di tutto questo sono più in basso

Verifica membro x in una determinata classe. Potrebbe essere var, func, class, union o enum:

CREATE_MEMBER_CHECK(x);
bool has_x = has_member_x<class_to_check_for_x>::value;

Controlla la funzione membro void x():

//Func signature MUST have T as template variable here... simpler this way :\
CREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);
bool has_func_sig_void__x = has_member_func_void__x<class_to_check_for_x>::value;

Controlla la variabile membro <=>:

CREATE_MEMBER_VAR_CHECK(x);
bool has_var_x = has_member_var_x<class_to_check_for_x>::value;

Verifica la classe membro <=>:

CREATE_MEMBER_CLASS_CHECK(x);
bool has_class_x = has_member_class_x<class_to_check_for_x>::value;

Verifica unione membri <=>:

CREATE_MEMBER_UNION_CHECK(x);
bool has_union_x = has_member_union_x<class_to_check_for_x>::value;

Verifica la presenza dei membri <=>:

CREATE_MEMBER_ENUM_CHECK(x);
bool has_enum_x = has_member_enum_x<class_to_check_for_x>::value;

Verifica la presenza di qualsiasi funzione membro <=> indipendentemente dalla firma:

CREATE_MEMBER_CHECK(x);
CREATE_MEMBER_VAR_CHECK(x);
CREATE_MEMBER_CLASS_CHECK(x);
CREATE_MEMBER_UNION_CHECK(x);
CREATE_MEMBER_ENUM_CHECK(x);
CREATE_MEMBER_FUNC_CHECK(x);
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

o

CREATE_MEMBER_CHECKS(x);  //Just stamps out the same macro calls as above.
bool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;

Dettagli e core:

/*
    - Multiple inheritance forces ambiguity of member names.
    - SFINAE is used to make aliases to member names.
    - Expression SFINAE is used in just one generic has_member that can accept
      any alias we pass it.
*/

//Variadic to force ambiguity of class members.  C++11 and up.
template <typename... Args> struct ambiguate : public Args... {};

//Non-variadic version of the line above.
//template <typename A, typename B> struct ambiguate : public A, public B {};

template<typename A, typename = void>
struct got_type : std::false_type {};

template<typename A>
struct got_type<A> : std::true_type {
    typedef A type;
};

template<typename T, T>
struct sig_check : std::true_type {};

template<typename Alias, typename AmbiguitySeed>
struct has_member {
    template<typename C> static char ((&f(decltype(&C::value))))[1];
    template<typename C> static char ((&f(...)))[2];

    //Make sure the member name is consistently spelled the same.
    static_assert(
        (sizeof(f<AmbiguitySeed>(0)) == 1)
        , "Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified."
    );

    static bool const value = sizeof(f<Alias>(0)) == 2;
};

Macro (El Diablo!):

CREATE_MEMBER_CHECK:

//Check for any member with given name, whether var, func, class, union, enum.
#define CREATE_MEMBER_CHECK(member)                                         \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct Alias_##member;                                                      \
                                                                            \
template<typename T>                                                        \
struct Alias_##member <                                                     \
    T, std::integral_constant<bool, got_type<decltype(&T::member)>::value>  \
> { static const decltype(&T::member) value; };                             \
                                                                            \
struct AmbiguitySeed_##member { char member; };                             \
                                                                            \
template<typename T>                                                        \
struct has_member_##member {                                                \
    static const bool value                                                 \
        = has_member<                                                       \
            Alias_##member<ambiguate<T, AmbiguitySeed_##member>>            \
            , Alias_##member<AmbiguitySeed_##member>                        \
        >::value                                                            \
    ;                                                                       \
}

CREATE_MEMBER_VAR_CHECK:

//Check for member variable with given name.
#define CREATE_MEMBER_VAR_CHECK(var_name)                                   \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct has_member_var_##var_name : std::false_type {};                      \
                                                                            \
template<typename T>                                                        \
struct has_member_var_##var_name<                                           \
    T                                                                       \
    , std::integral_constant<                                               \
        bool                                                                \
        , !std::is_member_function_pointer<decltype(&T::var_name)>::value   \
    >                                                                       \
> : std::true_type {}

CREATE_MEMBER_FUNC_SIG_CHECK:

//Check for member function with given name AND signature.
#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix)    \
                                                                            \
template<typename T, typename = std::true_type>                             \
struct has_member_func_##templ_postfix : std::false_type {};                \
                                                                            \
template<typename T>                                                        \
struct has_member_func_##templ_postfix<                                     \
    T, std::integral_constant<                                              \
        bool                                                                \
        , sig_check<func_sig, &T::func_name>::value                         \
    >                                                                       \
> : std::true_type {}

CREATE_MEMBER_CLASS_CHECK:

//Check for member class with given name.
#define CREATE_MEMBER_CLASS_CHECK(class_name)               \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_class_##class_name : std::false_type {};  \
                                                            \
template<typename T>                                        \
struct has_member_class_##class_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_class<                                    \
            typename got_type<typename T::class_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}

CREATE_MEMBER_UNION_CHECK:

//Check for member union with given name.
#define CREATE_MEMBER_UNION_CHECK(union_name)               \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_union_##union_name : std::false_type {};  \
                                                            \
template<typename T>                                        \
struct has_member_union_##union_name<                       \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_union<                                    \
            typename got_type<typename T::union_name>::type \
        >::value                                            \
    >                                                       \
> : std::true_type {}

CREATE_MEMBER_ENUM_CHECK:

//Check for member enum with given name.
#define CREATE_MEMBER_ENUM_CHECK(enum_name)                 \
                                                            \
template<typename T, typename = std::true_type>             \
struct has_member_enum_##enum_name : std::false_type {};    \
                                                            \
template<typename T>                                        \
struct has_member_enum_##enum_name<                         \
    T                                                       \
    , std::integral_constant<                               \
        bool                                                \
        , std::is_enum<                                     \
            typename got_type<typename T::enum_name>::type  \
        >::value                                            \
    >                                                       \
> : std::true_type {}

CREATE_MEMBER_FUNC_CHECK:

//Check for function with given name, any signature.
#define CREATE_MEMBER_FUNC_CHECK(func)          \
template<typename T>                            \
struct has_member_func_##func {                 \
    static const bool value                     \
        = has_member_##func<T>::value           \
        && !has_member_var_##func<T>::value     \
        && !has_member_class_##func<T>::value   \
        && !has_member_union_##func<T>::value   \
        && !has_member_enum_##func<T>::value    \
    ;                                           \
}

CREATE_MEMBER_CHECKS:

//Create all the checks for one member.  Does NOT include func sig checks.
#define CREATE_MEMBER_CHECKS(member)    \
CREATE_MEMBER_CHECK(member);            \
CREATE_MEMBER_VAR_CHECK(member);        \
CREATE_MEMBER_CLASS_CHECK(member);      \
CREATE_MEMBER_UNION_CHECK(member);      \
CREATE_MEMBER_ENUM_CHECK(member);       \
CREATE_MEMBER_FUNC_CHECK(member)

La soluzione C ++ standard presentata qui da litb non funzionerà come previsto se il metodo dovesse essere definito in una classe base.

Per una soluzione che gestisca questa situazione, consultare:

In russo: http://www.rsdn.ru/forum/message/2759773.1.aspx

Traduzione inglese di Roman.Perepelitsa: http: // groups .google.com / group / comp.lang.c ++. moderato / tree / browse_frm / thread / 4f7c7a96f9afbe44 / c95a7b4c645e449f? pli = 1

È follemente intelligente. Tuttavia, un problema con questa soluzione è che fornisce errori del compilatore se il tipo in fase di test è uno che non può essere utilizzato come classe di base (ad es. Tipi primitivi)

In Visual Studio, ho notato che se si lavora con il metodo senza argomenti, è necessario inserire una coppia extra di ridondanti () attorno agli argomenti per deduce () nell'espressione sizeof.

MSVC ha le parole chiave __if_exists e __if_not_exists ( Doc ). Insieme all'approccio typeof-SFINAE di Nicola ho potuto creare un controllo per GCC e MSVC come l'OP ha cercato.

Aggiornamento: la fonte può essere trovata Qui

Ho scritto una risposta a questo in un altro thread che (a differenza delle soluzioni sopra) controlla anche le funzioni membro ereditate:

SFINAE per verificare le funzioni membro ereditate

Ecco alcuni esempi di quella soluzione:

Esempio 1:

Stiamo cercando un membro con la seguente firma: T::const_iterator begin() const

template<class T> struct has_const_begin
{
    typedef char (&Yes)[1];
    typedef char (&No)[2];

    template<class U> 
    static Yes test(U const * data, 
                    typename std::enable_if<std::is_same<
                             typename U::const_iterator, 
                             decltype(data->begin())
                    >::value>::type * = 0);
    static No test(...);
    static const bool value = sizeof(Yes) == sizeof(has_const_begin::test((typename std::remove_reference<T>::type*)0));
};

Si noti che controlla anche la costanza del metodo e funziona anche con tipi primitivi. (Voglio dire has_const_begin<int>::value è falso e non causa un errore di compilazione.

Esempio 2

Ora stiamo cercando la firma: void foo(MyClass&, unsigned)

template<class T> struct has_foo
{
    typedef char (&Yes)[1];
    typedef char (&No)[2];

    template<class U>
    static Yes test(U * data, MyClass* arg1 = 0,
                    typename std::enable_if<std::is_void<
                             decltype(data->foo(*arg1, 1u))
                    >::value>::type * = 0);
    static No test(...);
    static const bool value = sizeof(Yes) == sizeof(has_foo::test((typename std::remove_reference<T>::type*)0));
};

Si noti che MyClass non deve essere costruibile di default o per soddisfare qualsiasi concetto speciale. La tecnica funziona anche con i membri del modello.

Attendo con impazienza opinioni in merito.

Ora questo era un simpatico rompicapo - ottima domanda!

Ecco un'alternativa alla La soluzione di Nicola Bonelli che non si basa sull'operatore typeof non standard.

Sfortunatamente, non funziona su GCC (MinGW) 3.4.5 o Digital Mars 8.42n, ma funziona su tutte le versioni di MSVC (incluso VC6) e su Comeau C ++.

Il blocco commenti più lungo ha i dettagli su come funziona (o dovrebbe funzionare). Come si dice, non sono sicuro di quale comportamento sia conforme agli standard - sarei lieto di commentare.


aggiornamento - 7 nov 2008:

Sembra che mentre questo codice sia sintatticamente corretto, il comportamento mostrato da MSVC e Comeau C ++ non segua lo standard (grazie a Leon Timmermans e litb per indicarmi la giusta direzione). Lo standard C ++ 03 dice quanto segue:

  

14.6.2 Nomi dipendenti [temp.dep]

     

Paragrafo 3

     

Nella definizione di un modello di classe   o un membro di un modello di classe, se a   classe base del modello di classe   dipende da un parametro-modello, il   l'ambito della classe base non viene esaminato   durante la ricerca del nome non qualificato   al punto di definizione di   modello di classe o membro o durante un   istanza del modello di classe o   membro.

Quindi, sembra che quando MSVC o Comeau considerano la toString() funzione membro di T eseguendo la ricerca del nome nel sito di chiamata in doToString() quando il modello è istanziato, ciò è errato (anche se in realtà è il comportamento che stavo cercando in questo caso).

Il comportamento di GCC e Digital Mars sembra essere corretto - in entrambi i casi la funzione <=> non membro è associata alla chiamata.

Ratti - Pensavo di aver trovato una soluzione intelligente, invece ho scoperto un paio di bug del compilatore ...


#include <iostream>
#include <string>

struct Hello
{
    std::string toString() {
        return "Hello";
    }
};

struct Generic {};


// the following namespace keeps the toString() method out of
//  most everything - except the other stuff in this
//  compilation unit

namespace {
    std::string toString()
    {
        return "toString not defined";
    }

    template <typename T>
    class optionalToStringImpl : public T
    {
    public:
        std::string doToString() {

            // in theory, the name lookup for this call to 
            //  toString() should find the toString() in 
            //  the base class T if one exists, but if one 
            //  doesn't exist in the base class, it'll 
            //  find the free toString() function in 
            //  the private namespace.
            //
            // This theory works for MSVC (all versions
            //  from VC6 to VC9) and Comeau C++, but
            //  does not work with MinGW 3.4.5 or 
            //  Digital Mars 8.42n
            //
            // I'm honestly not sure what the standard says 
            //  is the correct behavior here - it's sort 
            //  of like ADL (Argument Dependent Lookup - 
            //  also known as Koenig Lookup) but without
            //  arguments (except the implied "this" pointer)

            return toString();
        }
    };
}

template <typename T>
std::string optionalToString(T & obj)
{
    // ugly, hacky cast...
    optionalToStringImpl<T>* temp = reinterpret_cast<optionalToStringImpl<T>*>( &obj);

    return temp->doToString();
}



int
main(int argc, char *argv[])
{
    Hello helloObj;
    Generic genericObj;

    std::cout << optionalToString( helloObj) << std::endl;
    std::cout << optionalToString( genericObj) << std::endl;
    return 0;
}

Ho modificato la soluzione fornita in https://stackoverflow.com/a/264088/2712152 per renderla un un po 'più generale. Inoltre, poiché non utilizza nessuna delle nuove funzionalità di C ++ 11, possiamo usarlo con vecchi compilatori e dovrebbe funzionare anche con msvc. Ma i compilatori dovrebbero abilitare C99 a usarlo poiché usa macro variadiche.

La seguente macro può essere utilizzata per verificare se una determinata classe ha un particolare typedef o meno.

/** 
 * @class      : HAS_TYPEDEF
 * @brief      : This macro will be used to check if a class has a particular
 * typedef or not.
 * @param typedef_name : Name of Typedef
 * @param name  : Name of struct which is going to be run the test for
 * the given particular typedef specified in typedef_name
 */
#define HAS_TYPEDEF(typedef_name, name)                           \
   template <typename T>                                          \
   struct name {                                                  \
      typedef char yes[1];                                        \
      typedef char no[2];                                         \
      template <typename U>                                       \
      struct type_check;                                          \
      template <typename _1>                                      \
      static yes& chk(type_check<typename _1::typedef_name>*);    \
      template <typename>                                         \
      static no& chk(...);                                        \
      static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \
   }

La seguente macro può essere utilizzata per verificare se una determinata classe ha una particolare funzione membro o meno con un determinato numero di argomenti.

/** 
 * @class      : HAS_MEM_FUNC
 * @brief      : This macro will be used to check if a class has a particular
 * member function implemented in the public section or not. 
 * @param func : Name of Member Function
 * @param name : Name of struct which is going to be run the test for
 * the given particular member function name specified in func
 * @param return_type: Return type of the member function
 * @param ellipsis(...) : Since this is macro should provide test case for every
 * possible member function we use variadic macros to cover all possibilities
 */
#define HAS_MEM_FUNC(func, name, return_type, ...)                \
   template <typename T>                                          \
   struct name {                                                  \
      typedef return_type (T::*Sign)(__VA_ARGS__);                \
      typedef char yes[1];                                        \
      typedef char no[2];                                         \
      template <typename U, U>                                    \
      struct type_check;                                          \
      template <typename _1>                                      \
      static yes& chk(type_check<Sign, &_1::func>*);              \
      template <typename>                                         \
      static no& chk(...);                                        \
      static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \
   }

Possiamo usare le 2 macro precedenti per eseguire i controlli per has_typedef e has_mem_func come:

class A {
public:
  typedef int check;
  void check_function() {}
};

class B {
public:
  void hello(int a, double b) {}
  void hello() {}
};

HAS_MEM_FUNC(check_function, has_check_function, void, void);
HAS_MEM_FUNC(hello, hello_check, void, int, double);
HAS_MEM_FUNC(hello, hello_void_check, void, void);
HAS_TYPEDEF(check, has_typedef_check);

int main() {
  std::cout << "Check Function A:" << has_check_function<A>::value << std::endl;
  std::cout << "Check Function B:" << has_check_function<B>::value << std::endl;
  std::cout << "Hello Function A:" << hello_check<A>::value << std::endl;
  std::cout << "Hello Function B:" << hello_check<B>::value << std::endl;
  std::cout << "Hello void Function A:" << hello_void_check<A>::value << std::endl;
  std::cout << "Hello void Function B:" << hello_void_check<B>::value << std::endl;
  std::cout << "Check Typedef A:" << has_typedef_check<A>::value << std::endl;
  std::cout << "Check Typedef B:" << has_typedef_check<B>::value << std::endl;
}

Un esempio che utilizza SFINAE e la specializzazione parziale del modello, scrivendo un Has_foo controllo di concetto:

#include <type_traits>
struct A{};

struct B{ int foo(int a, int b);};

struct C{void foo(int a, int b);};

struct D{int foo();};

struct E: public B{};

// available in C++17 onwards as part of <type_traits>
template<typename...>
using void_t = void;

template<typename T, typename = void> struct Has_foo: std::false_type{};

template<typename T> 
struct Has_foo<T, void_t<
    std::enable_if_t<
        std::is_same<
            int, 
            decltype(std::declval<T>().foo((int)0, (int)0))
        >::value
    >
>>: std::true_type{};


static_assert(not Has_foo<A>::value, "A does not have a foo");
static_assert(Has_foo<B>::value, "B has a foo");
static_assert(not Has_foo<C>::value, "C has a foo with the wrong return. ");
static_assert(not Has_foo<D>::value, "D has a foo with the wrong arguments. ");
static_assert(Has_foo<E>::value, "E has a foo since it inherits from B");

Nessuno strano ha suggerito il seguente bel trucco che ho visto una volta proprio su questo sito:

template <class T>
struct has_foo
{
    struct S { void foo(...); };
    struct derived : S, T {};

    template <typename V, V> struct W {};

    template <typename X>
    char (&test(W<void (X::*)(), &X::foo> *))[1];

    template <typename>
    char (&test(...))[2];

    static const bool value = sizeof(test<derived>(0)) == 1;
};

Devi assicurarti che T sia una classe. Sembra che l'ambiguità nella ricerca del foo sia un fallimento di sostituzione. L'ho fatto funzionare su gcc, ma non sono sicuro che sia standard.

Il modello generico che può essere utilizzato per verificare se alcune " feature " è supportato dal tipo:

#include <type_traits>

template <template <typename> class TypeChecker, typename Type>
struct is_supported
{
    // these structs are used to recognize which version
    // of the two functions was chosen during overload resolution
    struct supported {};
    struct not_supported {};

    // this overload of chk will be ignored by SFINAE principle
    // if TypeChecker<Type_> is invalid type
    template <typename Type_>
    static supported chk(typename std::decay<TypeChecker<Type_>>::type *);

    // ellipsis has the lowest conversion rank, so this overload will be
    // chosen during overload resolution only if the template overload above is ignored
    template <typename Type_>
    static not_supported chk(...);

    // if the template overload of chk is chosen during
    // overload resolution then the feature is supported
    // if the ellipses overload is chosen the the feature is not supported
    static constexpr bool value = std::is_same<decltype(chk<Type>(nullptr)),supported>::value;
};

Il modello che controlla se esiste un metodo foo compatibile con la firma double(const char*)

// if T doesn't have foo method with the signature that allows to compile the bellow
// expression then instantiating this template is Substitution Failure (SF)
// which Is Not An Error (INAE) if this happens during overload resolution
template <typename T>
using has_foo = decltype(double(std::declval<T>().foo(std::declval<const char*>())));

Esempi

// types that support has_foo
struct struct1 { double foo(const char*); };            // exact signature match
struct struct2 { int    foo(const std::string &str); }; // compatible signature
struct struct3 { float  foo(...); };                    // compatible ellipsis signature
struct struct4 { template <typename T>
                 int    foo(T t); };                    // compatible template signature

// types that do not support has_foo
struct struct5 { void        foo(const char*); }; // returns void
struct struct6 { std::string foo(const char*); }; // std::string can't be converted to double
struct struct7 { double      foo(      int *); }; // const char* can't be converted to int*
struct struct8 { double      bar(const char*); }; // there is no foo method

int main()
{
    std::cout << std::boolalpha;

    std::cout << is_supported<has_foo, int    >::value << std::endl; // false
    std::cout << is_supported<has_foo, double >::value << std::endl; // false

    std::cout << is_supported<has_foo, struct1>::value << std::endl; // true
    std::cout << is_supported<has_foo, struct2>::value << std::endl; // true
    std::cout << is_supported<has_foo, struct3>::value << std::endl; // true
    std::cout << is_supported<has_foo, struct4>::value << std::endl; // true

    std::cout << is_supported<has_foo, struct5>::value << std::endl; // false
    std::cout << is_supported<has_foo, struct6>::value << std::endl; // false
    std::cout << is_supported<has_foo, struct7>::value << std::endl; // false
    std::cout << is_supported<has_foo, struct8>::value << std::endl; // false

    return 0;
}

http://coliru.stacked-crooked.com/a/83c6a631ed42cea4

Ci sono molte risposte qui, ma non sono riuscito a trovare una versione che esegua l'ordinamento della risoluzione del metodo reale , senza utilizzare nessuna delle nuove funzionalità c ++ (usando solo c ++ 98 caratteristiche).
Nota: questa versione è stata testata e funziona con vc ++ 2013, g ++ 5.2.0 e il compilatore online.

Quindi ho ideato una versione che utilizza solo sizeof ():

template<typename T> T declval(void);

struct fake_void { };
template<typename T> T &operator,(T &,fake_void);
template<typename T> T const &operator,(T const &,fake_void);
template<typename T> T volatile &operator,(T volatile &,fake_void);
template<typename T> T const volatile &operator,(T const volatile &,fake_void);

struct yes { char v[1]; };
struct no  { char v[2]; };
template<bool> struct yes_no:yes{};
template<> struct yes_no<false>:no{};

template<typename T>
struct has_awesome_member {
 template<typename U> static yes_no<(sizeof((
   declval<U>().awesome_member(),fake_void()
  ))!=0)> check(int);
 template<typename> static no check(...);
 enum{value=sizeof(check<T>(0)) == sizeof(yes)};
};


struct foo { int awesome_member(void); };
struct bar { };
struct foo_void { void awesome_member(void); };
struct wrong_params { void awesome_member(int); };

static_assert(has_awesome_member<foo>::value,"");
static_assert(!has_awesome_member<bar>::value,"");
static_assert(has_awesome_member<foo_void>::value,"");
static_assert(!has_awesome_member<wrong_params>::value,"");

Demo live (con controllo del tipo di reso esteso e soluzione alternativa a vc ++ 2010): http://cpp.sh/5b2vs

Nessuna fonte, dato che me ne sono inventato io.

Quando si esegue la demo live sul compilatore g ++, tenere presente che sono consentite dimensioni di array pari a 0, il che significa che static_assert utilizzato non attiverà un errore del compilatore, anche se non riesce.
Una soluzione alternativa comunemente usata è quella di sostituire "typedef" nella macro con "extern".

Che ne dici di questa soluzione?

#include <type_traits>

template <typename U, typename = void> struct hasToString : std::false_type { };

template <typename U>
struct hasToString<U,
  typename std::enable_if<bool(sizeof(&U::toString))>::type
> : std::true_type { };

Ecco la mia versione che gestisce tutti i possibili sovraccarichi delle funzioni membro con arità arbitraria, comprese le funzioni membro modello, possibilmente con argomenti predefiniti. Distingue 3 scenari reciprocamente esclusivi quando si effettua una chiamata di funzione membro a un tipo di classe, con determinati tipi arg: (1) valido, (2) ambiguo o (3) non praticabile. Esempio di utilizzo:

#include <string>
#include <vector>

HAS_MEM(bar)
HAS_MEM_FUN_CALL(bar)

struct test
{
   void bar(int);
   void bar(double);
   void bar(int,double);

   template < typename T >
   typename std::enable_if< not std::is_integral<T>::value >::type
   bar(const T&, int=0){}

   template < typename T >
   typename std::enable_if< std::is_integral<T>::value >::type
   bar(const std::vector<T>&, T*){}

   template < typename T >
   int bar(const std::string&, int){}
};

Ora puoi usarlo in questo modo:

int main(int argc, const char * argv[])
{
   static_assert( has_mem_bar<test>::value , "");

   static_assert( has_valid_mem_fun_call_bar<test(char const*,long)>::value , "");
   static_assert( has_valid_mem_fun_call_bar<test(std::string&,long)>::value , "");

   static_assert( has_valid_mem_fun_call_bar<test(std::vector<int>, int*)>::value , "");
   static_assert( has_no_viable_mem_fun_call_bar<test(std::vector<double>, double*)>::value , "");

   static_assert( has_valid_mem_fun_call_bar<test(int)>::value , "");
   static_assert( std::is_same<void,result_of_mem_fun_call_bar<test(int)>::type>::value , "");

   static_assert( has_valid_mem_fun_call_bar<test(int,double)>::value , "");
   static_assert( not has_valid_mem_fun_call_bar<test(int,double,int)>::value , "");

   static_assert( not has_ambiguous_mem_fun_call_bar<test(double)>::value , "");
   static_assert( has_ambiguous_mem_fun_call_bar<test(unsigned)>::value , "");

   static_assert( has_viable_mem_fun_call_bar<test(unsigned)>::value , "");
   static_assert( has_viable_mem_fun_call_bar<test(int)>::value , "");

   static_assert( has_no_viable_mem_fun_call_bar<test(void)>::value , "");

   return 0;
}

Ecco il codice, scritto in c ++ 11, tuttavia, puoi facilmente portarlo (con piccole modifiche) a non c ++ 11 che ha estensioni di tipo (ad esempio gcc). Puoi sostituire la macro HAS_MEM con la tua.

#pragma once

#if __cplusplus >= 201103

#include <utility>
#include <type_traits>

#define HAS_MEM(mem)                                                                                     \
                                                                                                     \
template < typename T >                                                                               \
struct has_mem_##mem                                                                                  \
{                                                                                                     \
  struct yes {};                                                                                     \
  struct no  {};                                                                                     \
                                                                                                     \
  struct ambiguate_seed { char mem; };                                                               \
  template < typename U > struct ambiguate : U, ambiguate_seed {};                                   \
                                                                                                     \
  template < typename U, typename = decltype(&U::mem) > static constexpr no  test(int);              \
  template < typename                                 > static constexpr yes test(...);              \
                                                                                                     \
  static bool constexpr value = std::is_same<decltype(test< ambiguate<T> >(0)),yes>::value ;         \
  typedef std::integral_constant<bool,value>    type;                                                \
};


#define HAS_MEM_FUN_CALL(memfun)                                                                         \
                                                                                                     \
template < typename Signature >                                                                       \
struct has_valid_mem_fun_call_##memfun;                                                               \
                                                                                                     \
template < typename T, typename... Args >                                                             \
struct has_valid_mem_fun_call_##memfun< T(Args...) >                                                  \
{                                                                                                     \
  struct yes {};                                                                                     \
  struct no  {};                                                                                     \
                                                                                                     \
  template < typename U, bool = has_mem_##memfun<U>::value >                                         \
  struct impl                                                                                        \
  {                                                                                                  \
     template < typename V, typename = decltype(std::declval<V>().memfun(std::declval<Args>()...)) > \
     struct test_result { using type = yes; };                                                       \
                                                                                                     \
     template < typename V > static constexpr typename test_result<V>::type test(int);               \
     template < typename   > static constexpr                            no test(...);               \
                                                                                                     \
     static constexpr bool value = std::is_same<decltype(test<U>(0)),yes>::value;                    \
     using type = std::integral_constant<bool, value>;                                               \
  };                                                                                                 \
                                                                                                     \
  template < typename U >                                                                            \
  struct impl<U,false> : std::false_type {};                                                         \
                                                                                                     \
  static constexpr bool value = impl<T>::value;                                                      \
  using type = std::integral_constant<bool, value>;                                                  \
};                                                                                                    \
                                                                                                     \
template < typename Signature >                                                                       \
struct has_ambiguous_mem_fun_call_##memfun;                                                           \
                                                                                                     \
template < typename T, typename... Args >                                                             \
struct has_ambiguous_mem_fun_call_##memfun< T(Args...) >                                              \
{                                                                                                     \
  struct ambiguate_seed { void memfun(...); };                                                       \
                                                                                                     \
  template < class U, bool = has_mem_##memfun<U>::value >                                            \
  struct ambiguate : U, ambiguate_seed                                                               \
  {                                                                                                  \
    using ambiguate_seed::memfun;                                                                    \
    using U::memfun;                                                                                 \
  };                                                                                                 \
                                                                                                     \
  template < class U >                                                                               \
  struct ambiguate<U,false> : ambiguate_seed {};                                                     \
                                                                                                     \
  static constexpr bool value = not has_valid_mem_fun_call_##memfun< ambiguate<T>(Args...) >::value; \
  using type = std::integral_constant<bool, value>;                                                  \
};                                                                                                    \
                                                                                                     \
template < typename Signature >                                                                       \
struct has_viable_mem_fun_call_##memfun;                                                              \
                                                                                                     \
template < typename T, typename... Args >                                                             \
struct has_viable_mem_fun_call_##memfun< T(Args...) >                                                 \
{                                                                                                     \
  static constexpr bool value = has_valid_mem_fun_call_##memfun<T(Args...)>::value                   \
                             or has_ambiguous_mem_fun_call_##memfun<T(Args...)>::value;              \
  using type = std::integral_constant<bool, value>;                                                  \
};                                                                                                    \
                                                                                                     \
template < typename Signature >                                                                       \
struct has_no_viable_mem_fun_call_##memfun;                                                           \
                                                                                                     \
template < typename T, typename... Args >                                                             \
struct has_no_viable_mem_fun_call_##memfun < T(Args...) >                                             \
{                                                                                                     \
  static constexpr bool value = not has_viable_mem_fun_call_##memfun<T(Args...)>::value;             \
  using type = std::integral_constant<bool, value>;                                                  \
};                                                                                                    \
                                                                                                     \
template < typename Signature >                                                                       \
struct result_of_mem_fun_call_##memfun;                                                               \
                                                                                                     \
template < typename T, typename... Args >                                                             \
struct result_of_mem_fun_call_##memfun< T(Args...) >                                                  \
{                                                                                                     \
  using type = decltype(std::declval<T>().memfun(std::declval<Args>()...));                          \
};

#endif

Puoi saltare tutta la metaprogrammazione in C ++ 14 e scriverla semplicemente usando fit::conditional dalla Adatta libreria:

template<class T>
std::string optionalToString(T* x)
{
    return fit::conditional(
        [](auto* obj) -> decltype(obj->toString()) { return obj->toString(); },
        [](auto*) { return "toString not defined"; }
    )(x);
}

Puoi anche creare la funzione direttamente anche dai lambda:

FIT_STATIC_LAMBDA_FUNCTION(optionalToString) = fit::conditional(
    [](auto* obj) -> decltype(obj->toString(), std::string()) { return obj->toString(); },
    [](auto*) -> std::string { return "toString not defined"; }
);

Tuttavia, se si utilizza un compilatore che non supporta lambda generici, sarà necessario scrivere oggetti funzione separati:

struct withToString
{
    template<class T>
    auto operator()(T* obj) const -> decltype(obj->toString(), std::string())
    {
        return obj->toString();
    }
};

struct withoutToString
{
    template<class T>
    std::string operator()(T*) const
    {
        return "toString not defined";
    }
};

FIT_STATIC_FUNCTION(optionalToString) = fit::conditional(
    withToString(),
    withoutToString()
);

Ecco un esempio del codice funzionante.

template<typename T>
using toStringFn = decltype(std::declval<const T>().toString());

template <class T, toStringFn<T>* = nullptr>
std::string optionalToString(const T* obj, int)
{
    return obj->toString();
}

template <class T>
std::string optionalToString(const T* obj, long)
{
    return "toString not defined";
}

int main()
{
    A* a;
    B* b;

    std::cout << optionalToString(a, 0) << std::endl; // This is A
    std::cout << optionalToString(b, 0) << std::endl; // toString not defined
}

toStringFn<T>* = nullptr abiliterà la funzione che accetta un ulteriore int argomento che ha una priorità sulla funzione che assume long quando viene chiamato con 0.

È possibile utilizzare lo stesso principio per le funzioni che restituiscono true se la funzione è implementata.

template <typename T>
constexpr bool toStringExists(long)
{
    return false;
}

template <typename T, toStringFn<T>* = nullptr>
constexpr bool toStringExists(int)
{
    return true;
}


int main()
{
    A* a;
    B* b;

    std::cout << toStringExists<A>(0) << std::endl; // true
    std::cout << toStringExists<B>(0) << std::endl; // false
}

Ho avuto un problema simile:

Una classe modello che può essere derivata da alcune classi base, alcune con un determinato membro e altre che non lo fanno.

L'ho risolto in modo simile al " typeof " (La risposta di Nicola Bonelli), ma con decltype in modo che compili e funzioni correttamente su MSVS:

#include <iostream>
#include <string>

struct Generic {};    
struct HasMember 
{
  HasMember() : _a(1) {};
  int _a;
};    

// SFINAE test
template <typename T>
class S : public T
{
public:
  std::string foo (std::string b)
  {
    return foo2<T>(b,0);
  }

protected:
  template <typename T> std::string foo2 (std::string b, decltype (T::_a))
  {
    return b + std::to_string(T::_a);
  }
  template <typename T> std::string foo2 (std::string b, ...)
  {
    return b + "No";
  }
};

int main(int argc, char *argv[])
{
  S<HasMember> d1;
  S<Generic> d2;

  std::cout << d1.foo("HasMember: ") << std::endl;
  std::cout << d2.foo("Generic: ") << std::endl;
  return 0;
}
template<class T>
auto optionalToString(T* obj)
->decltype( obj->toString(), std::string() )
{
     return obj->toString();
}

template<class T>
auto optionalToString(T* obj)
->decltype( std::string() )
{
     throw "Error!";
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top