Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [C++] Template non-const lvalue ref

    Ciao a tutti,
    nello sviluppo di un progetto personale mi sono trovato davanti alla necessità di avere una funzione che accetti come parametro solo un reference a un template parameter non-const.

    Ho provato con qualcosa tipo:
    codice:
    template<typename T>
    struct foo
    {
        using func_t = std::function<void(T&)>;
    
        static void setFunc(const func_t&) {}
        static func_t func() {}
    };
    Ma così facendo accetta qualsiasi tipo di lvalue e non solo le reference a quelli non-const.

    Qualche idea?

  2. #2
    http://en.cppreference.com/w/cpp/types/is_reference
    http://en.cppreference.com/w/cpp/types/is_const
    http://en.cppreference.com/w/cpp/language/static_assert
    codice:
    template<typename T>
    struct foo
    {
        static_assert(!std::is_reference(T)::value || std::is_const(T)::value, "T needs to be a non-const reference);
        using func_t = std::function<void(T&)>;
    
        static void setFunc(const func_t&) {}
        static func_t func() {}
    };
    Amaro C++, il gusto pieno dell'undefined behavior.

  3. #3
    Penso tu abbia frainteso. Quello che voglio controllare è che il parametro che accetta func_t sia non-const ref e non T.

    Esempio:
    codice:
    auto f1 = std::bind( [](int&) {  }, std::placeholders::_1);         // int&
    auto f2 = std::bind( [](int) {}, std::placeholders::_1);             // int
    auto f3 = std::bind( [](const int) {}, std::placeholders::_1);    // const int
    
    foo<int>::setFunc(f1);         // ok int& (non-const ref)
    foo<int>::setFunc(f2);         // err int (non-const lvalue)
    foo<int>::setFunc(f3);         // err const int (const lvalue)


    Uno dei miei tentativi era qualcosa di questo tipo:
    codice:
    template<typename T>
    struct foo
    {
        using func_t = std::function<void(T&)>;
    
        static void useFunc() 
        { 
            static_assert(!std::is_reference<T&>::value ||
                          std::is_const<T&>,
                          "static_assert failed");
            _func(_t); 
        }
        static void setFunc(const func_t&) {}
        static func_t func() {}
        static func_t _func;
        static T _t;
    };


    Tuttavia anche questo tentativo fallisce perché la funzione che vado a passare può accettare qualsiasi tipo di lvalue, probabilmente mi sfugge qualcosa nella template argument deduction (di cui so poco).

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.