Domanda

mi chiedo perché std::function è a conoscenza solo delle funzioni a due argomenti. Ho scritto del codice che funziona bene, ma ci sono una serie di limitazioni. Qualsiasi feedback benvenuto. In particolare, sospetto che sto reinventando la ruota.

Il mio codice è acceso ideone E mi riferirò ad esso.

Ad esempio, posso descrivere il tipo di main insieme a:

function_type_deducer(main).describe_me();
// Output: I return i and I take 2 arguments.  They are of type:  i PPc

(dove "i" significa "int" e "ppc" significa puntatore-pointer-to-car)

Standard std::function Non funziona con le funzioni con più di due Args (vedere le ultime due righe del mio codice), ma questo codice lo fa (il codice di esempio mostra funzioni a tre ARG). Forse il mio design dovrebbe essere utilizzato nella libreria standard! Definisco typedef tuple<Args...> args_as_tuple; Per conservare tutti gli argomti, non solo i primi due tipi di argomenti.

Il trucco principale è la detrazione in questa funzione:

template<class T, class... Args>
auto function_type_deducer(T(Args...)) -> Function__<T, Args...> {
        return Function__<T, Args...> {};
}

Limitazioni:

  • Non funziona con Lambdas. Questo non si compilerà function_type_deducer([](){}).describe_me();
  • Non si nota che c'è una piccola differenza tra x e y, come y prende un string&, dove x prende un string. (La funzione std :: non lo nota neanche questo)

Qualche idea su come correggere una di queste? Ho reinventato la ruota?

È stato utile?

Soluzione

Questo non si compilerà function_type_deducer([](){}).describe_me();

Funzionerebbe se function_type_deducer non era un modello. :) Lambdas non catturato (vuoto []) sono implicitamente convertibili in puntatori di funzionalità. Purtroppo, le conversioni implicite non vengono prese in considerazione per la detrazione dell'argomento dei modelli. Vedere questa domanda Per ulteriori informazioni (si noti che la mia risposta non è completamente corretta come indicano i commenti).


Non si nota che c'è una piccola differenza tra X e Y, poiché Y prende una stringa e, dove X prende una stringa.

Non è un problema con la funzione, questo è un problema con typeid, come mostra questo semplice codice di prova:

template<class T>
void x(void(T)){
    T v;
    (void)v;
}

void f1(int){}
void f2(int&){}

int main(){
    x(f1);
    x(f2);
}

Esempio dal vivo su Ideone. Produzione:

Errore: "V" dichiarato come riferimento ma non inizializzato

Una soluzione semplice potrebbe essere l'utilizzo della spedizione di tag:

#include <type_traits> // is_reference
#include <iostream>
#include <typeinfo>

template<class T>
void print_name(std::true_type){
  std::cout << "reference to " << typeid(T).name();
}

template<class T>
void print_name(std::false_type){
  std::cout << typeid(T).name();
}

template<class T>
void print_name(){
  print_name(typename std::is_reference<T>::type());
}

E chiama print_name<NextArg>() invece di typeid(NextArg).name().


Ho reinventato la ruota?

Sì, un po 'e no, non l'hai fatto. Boost.function Fornisce typedefs per tutti gli argomenti (argN_type stile), anche come la costante statica arity per il suo numero. Tuttavia, non è possibile accedere facilmente a questi typedef genericamente. Avresti bisogno di un modo di rotonda per non accedere a quelli non esistenti. Il tuple L'idea funziona meglio, tuttavia può essere scritto in modo più bello. Ecco una versione modificata di qualcosa che una volta ho scritto:

#include <tuple>
#include <type_traits>
#include <iostream>
#include <typeinfo>

namespace detail{

template<class T>
std::ostream& print_name(std::ostream& os);

template<class T>
std::ostream& print_pointer(std::ostream& os, std::true_type){
  typedef typename std::remove_pointer<T>:: type np_type;
  os << "pointer to ";
  return print_name<np_type>(os);
}

template<class T>
std::ostream& print_pointer(std::ostream& os, std::false_type){
  return os << typeid(T).name();
}

template<class T>
std::ostream& print_name(std::ostream& os, std::true_type){
  return os << "reference to " << typeid(T).name();
}

template<class T>
std::ostream& print_name(std::ostream& os, std::false_type){
  return print_pointer<T>(os, typename std::is_pointer<T>::type());
}

template<class T>
std::ostream& print_name(std::ostream& os){
  return print_name<T>(os, typename std::is_reference<T>::type());
}

// to workaround partial function specialization
template<unsigned> struct int2type{};

template<class Tuple, unsigned I>
std::ostream& print_types(std::ostream& os, int2type<I>){
  typedef typename std::tuple_element<I,Tuple>::type type;

  print_types<Tuple>(os, int2type<I-1>()); // left-folding
  os << ", ";
  return print_name<type>(os);
}

template<class Tuple>
std::ostream& print_types(std::ostream& os, int2type<0>){
  typedef typename std::tuple_element<0,Tuple>::type type;
  return print_name<type>(os);
}

} // detail::

template<class R, class... Args>
struct function_info{
  typedef R result_type;
  typedef std::tuple<Args...> argument_tuple;
  static unsigned const arity = sizeof...(Args);

  void describe_me(std::ostream& os = std::cout) const{
    using namespace detail;
    os << "I return '"; print_name<result_type>(os);
    os << "' and I take '" << arity << "' arguments. They are: \n\t'";
    print_types<argument_tuple>(os, int2type<arity-1>()) << "'\n";
  }
};

Esempio dal vivo su Ideone. Produzione:

main:   I return 'i' and I take '2' arguments. They are: 
        'i, pointer to pointer to c'
x:      I return 'Ss' and I take '3' arguments. They are: 
        'i, Ss, c'
y:      I return 'Ss' and I take '3' arguments. They are: 
       'i, reference to Ss, c'

Altri suggerimenti

Il collegamento alla risposta con la funzione Lambda fornisce il suggerimento critico: è necessario ottenere un puntatore a una funzione membro per l'operatore di chiamata di funzione. Cioè se T è un oggetto funzione, devi guardare &T::operator(). Con Sfinae generalizzate è possibile determinare se esiste questo operatore di chiamata di funzione. Mettendo insieme queste cose in un modo forse in qualche modo rotonda, produce questo (che si compila con una versione recente di GCC e Clang, ad eccezione della funzione Lambda che non è ancora supportata da Clang):

#include <iostream>
#include <sstream>
#include <string>
#include <typeinfo>
#include <functional>
#include <utility>

// -----------------------------------------------------------------------------

struct S {
    void f(int, std::string&, void (*)(int)) {}
    void g(int, std::string&, void (*)(int)) const {}
};

// -----------------------------------------------------------------------------

template <typename T> struct describer;
template <> struct describer<S>;
template <> struct describer<int>;
template <> struct describer<void>;
template <> struct describer<std::string>;
template <typename T> struct describer<T&>;
template <typename T> struct describer<T*>;
template <typename T> struct describer<T const>;
template <typename T> struct describer<T volatile>;
template <typename T> struct describer<T const volatile>;
template <typename T, int Size> struct describer<T(&)[Size]>;

template <typename T> struct describer {
    static std::string type() { return "???"; }
};
template <> struct describer<S> {
    static std::string type() { return "S"; }
};
template <> struct describer<void> {
    static std::string type() { return "void"; }
};
template <> struct describer<int> {
    static std::string type() { return "int"; }
};
template <> struct describer<std::string> {
    static std::string type() { return "std::string"; }
};
template <typename T> struct describer<T&> {
    static std::string type() { return describer<T>::type() + std::string("&"); }
};
template <typename T> struct describer<T&&> {
    static std::string type() { return describer<T>::type() + std::string("&&"); }
};
template <typename T> struct describer<T*> {
    static std::string type() { return describer<T>::type() + std::string("&"); }
};
template <typename T> struct describer<T const> {
    static std::string type() { return describer<T>::type() + std::string(" const"); }
};
template <typename T> struct describer<T volatile> {
    static std::string type() { return describer<T>::type() + std::string(" volatile"); }
};
template <typename T> struct describer<T const volatile> {
    static std::string type() { return describer<T>::type() + std::string(" const volatile"); }
};
template <typename T, int Size> struct describer<T(&)[Size]>
{
    static std::string type() {
        std::ostringstream out;
        out << "(array of " << Size << " " << describer<T>::type() << " objects)&";
        return out.str();
    }
};

template <typename... T> struct description_list;
template <> struct description_list<> { static std::string type() { return std::string(); } }; 
template <typename T> struct description_list<T> { static std::string type() { return describer<T>::type(); } };
template <typename T, typename... S> struct description_list<T, S...> {
    static std::string type() { return describer<T>::type() + ", " + description_list<S...>::type(); }
};

template <typename R, typename... A>
struct describer<R(*)(A...)>
{
    static std::string type() {
        return "pointer function returning " + describer<R>::type() + " and taking arguments"
            + "(" + description_list<A...>::type() + ")";
    }
};

template <typename R, typename S, typename... A>
struct describer<R(S::*)(A...)>
{
    static std::string type() {
        return "pointer to member function of " + describer<S>::type() + " returning " + describer<R>::type() + " "
            "and taking arguments" + "(" + description_list<A...>::type() + ")";
    }
};

template <typename R, typename S, typename... A>
struct describer<R(S::*)(A...) const>
{
    static std::string type() {
        return "pointer to const member function of " + describer<S>::type() + " returning " + describer<R>::type() + " "
            "and taking arguments" + "(" + description_list<A...>::type() + ")";
    }
};

template <typename T> char (&call_op(decltype(&T::operator())*))[1];
template <typename T> char (&call_op(...))[2];

template <typename T> struct has_function_call_operator { enum { value = sizeof(call_op<T>(0)) == 1 }; };

template <typename T>
typename std::enable_if<!has_function_call_operator<T>::value>::type describe(std::string const& what, T)
{
    std::cout << "describe(" << what << ")=" << describer<T>::type() << "\n";
}

template <typename T>
typename std::enable_if<has_function_call_operator<T>::value>::type describe(std::string const& what, T)
{
    std::cout << "describe(" << what << ")=function object: " << describer<decltype(&T::operator())>::type() << "\n";
}


int f(std::string, std::string const&, std::string&&) { return 0; }
int g(std::string&, std::string const&) { return 0; }

int main()
{
    describe("int", 1);
    describe("f", &f);
    describe("g", &g);
    describe("S::f", &S::f);
    describe("S::g", &S::g);
    describe("mini-lambda", []{}); // doesn't work with clang, yet.
    describe("std::function<int(int(&)[1], int(&)[2], int(&)[4], int(&)[4])>",
             std::function<int(int(&)[1], int(&)[2], int(&)[4], int(&)[4])>());
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top