How to check whether variable of given type can be dereferenced?Template function for detecting pointer like (dereferencable) types fails for actual pointer typesHow can I profile C++ code running on Linux?Function passed as template argumentStatic constant string (class member)C++ metafunction to determine whether a type is callableImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow is “int main()(([]())());” valid C++?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsenum to string in modern C++11 / C++14 / C++17 and future C++20Are == and != mutually dependent?Does the C++ standard require operator != must be provided for a given iterator type?

Would molten tin solidify and coat an organic horn?

Has the speed of light ever been measured in vacuum?

What would cause a nuclear power plant to break down after 2000 years, but not sooner?

What does 〇〇〇〇 mean when combined with おじさん?

When does The Truman Show take place?

What are these panels underneath the wing root of a A380?

Why do we use low resistance cables to minimize power losses?

Can anybody tell me who this Pokemon is?

Duplicate and slide edge (rip from boundary)

Does Reckless Attack work with Multiattack when wild shaped?

Weird resistor with dots around it on the schematic

Does the Haste spell's hasted action allow you to make multiple unarmed strikes? Or none at all?

Did Michelle Obama have a staff of 23; and Melania have a staff of 4?

What modifiers are added to the attack and damage rolls of this unique longbow from Waterdeep: Dragon Heist?

Can I use my OWN published papers' images in my thesis without Copyright infringment

What's the relationship betweeen MS-DOS and XENIX?

What was the intention with the Commodore 128?

What's a good pattern to calculate a variable only when it is used the first time?

Quick destruction of a helium filled airship?

100 Years of GCHQ - A quick afternoon puzzle!

Meaning of だけはわからない

What is the purpose/function of this power inductor in parallel?

Do I need to start off my book by describing the character's "normal world"?

Have there ever been other TV shows or Films that told a similiar story to the new 90210 show?



How to check whether variable of given type can be dereferenced?


Template function for detecting pointer like (dereferencable) types fails for actual pointer typesHow can I profile C++ code running on Linux?Function passed as template argumentStatic constant string (class member)C++ metafunction to determine whether a type is callableImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow is “int main()(([]())());” valid C++?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsenum to string in modern C++11 / C++14 / C++17 and future C++20Are == and != mutually dependent?Does the C++ standard require operator != must be provided for a given iterator type?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Is there way in C++ to determine whether type of variable is pointer or any iterator with overloaded operator*?



There is standard std::is_pointer, but it say nothing about iterators.



I wanna use it in code like this:



template<class T>
void func(T var)

if constexpr (can_be_dereferenced<T>::value)

// do something with *var;











share|improve this question
























  • All standard library iterators have certain well defined members, like value_type. You should be able to come up with some SFINAE-based approach that checks for their existence. Or, make use of std::iterator_traits.

    – Sam Varshavchik
    Mar 27 at 12:34







  • 1





    Check this: stackoverflow.com/a/49904914/11224588

    – Diodacus
    Mar 27 at 12:40

















0















Is there way in C++ to determine whether type of variable is pointer or any iterator with overloaded operator*?



There is standard std::is_pointer, but it say nothing about iterators.



I wanna use it in code like this:



template<class T>
void func(T var)

if constexpr (can_be_dereferenced<T>::value)

// do something with *var;











share|improve this question
























  • All standard library iterators have certain well defined members, like value_type. You should be able to come up with some SFINAE-based approach that checks for their existence. Or, make use of std::iterator_traits.

    – Sam Varshavchik
    Mar 27 at 12:34







  • 1





    Check this: stackoverflow.com/a/49904914/11224588

    – Diodacus
    Mar 27 at 12:40













0












0








0


1






Is there way in C++ to determine whether type of variable is pointer or any iterator with overloaded operator*?



There is standard std::is_pointer, but it say nothing about iterators.



I wanna use it in code like this:



template<class T>
void func(T var)

if constexpr (can_be_dereferenced<T>::value)

// do something with *var;











share|improve this question














Is there way in C++ to determine whether type of variable is pointer or any iterator with overloaded operator*?



There is standard std::is_pointer, but it say nothing about iterators.



I wanna use it in code like this:



template<class T>
void func(T var)

if constexpr (can_be_dereferenced<T>::value)

// do something with *var;








c++ typetraits






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 12:33









dinpindinpin

32 bronze badges




32 bronze badges















  • All standard library iterators have certain well defined members, like value_type. You should be able to come up with some SFINAE-based approach that checks for their existence. Or, make use of std::iterator_traits.

    – Sam Varshavchik
    Mar 27 at 12:34







  • 1





    Check this: stackoverflow.com/a/49904914/11224588

    – Diodacus
    Mar 27 at 12:40

















  • All standard library iterators have certain well defined members, like value_type. You should be able to come up with some SFINAE-based approach that checks for their existence. Or, make use of std::iterator_traits.

    – Sam Varshavchik
    Mar 27 at 12:34







  • 1





    Check this: stackoverflow.com/a/49904914/11224588

    – Diodacus
    Mar 27 at 12:40
















All standard library iterators have certain well defined members, like value_type. You should be able to come up with some SFINAE-based approach that checks for their existence. Or, make use of std::iterator_traits.

– Sam Varshavchik
Mar 27 at 12:34






All standard library iterators have certain well defined members, like value_type. You should be able to come up with some SFINAE-based approach that checks for their existence. Or, make use of std::iterator_traits.

– Sam Varshavchik
Mar 27 at 12:34





1




1





Check this: stackoverflow.com/a/49904914/11224588

– Diodacus
Mar 27 at 12:40





Check this: stackoverflow.com/a/49904914/11224588

– Diodacus
Mar 27 at 12:40












2 Answers
2






active

oldest

votes


















3














You basically want to check if *var is valid. This is the perfect use case for a SFINAE check:



#include <type_traits>
#include <utility>

namespace detail
// If `*(object of type T)` is valid, this is selected and
// the return type is `std::true_type`
template<class T>
decltype(static_cast<void>(*std::declval<T>()), std::true_type)
can_be_dereferenced_impl(int);

// Otherwise the less specific function is selected,
// and the return type is `std::false_type`
template<class>
std::false_type can_be_dereferenced_impl(...);


template<class T>
struct can_be_dereferenced : decltype(detail::can_be_dereferenced_impl<T>(0)) ;

template<class T>
void func(T var)

if constexpr (can_be_dereferenced<T&>::value)
// Or can_be_dereferenced<decltype((var))>::value

auto&& dereferenced = *var;
// Use dereferenced







share|improve this answer

























  • This is exactly what I needed. Thanks a lot!

    – dinpin
    Mar 27 at 13:42


















0














You might do it in this way using compile time function overload resolution and SFINAE:



template<class T, typename = std::enable_if_t<std::is_pointer<T>::value>>
void func(T var)

// a pointer


template<class T, typename = std::enable_if_t<!std::is_pointer<T>::value>,
typename = T::value_type>
void func(T var)

// possibly an iterator


int main()
{
int *i = new int(11);
func(i); // Calls the first overload

std::vector<int> v;
std::vector<int>::const_iterator it = v.begin();

func(it); // Calls the second overload

func(2); // Fail, as there is no function for this argument.
[..]





share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55377316%2fhow-to-check-whether-variable-of-given-type-can-be-dereferenced%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You basically want to check if *var is valid. This is the perfect use case for a SFINAE check:



    #include <type_traits>
    #include <utility>

    namespace detail
    // If `*(object of type T)` is valid, this is selected and
    // the return type is `std::true_type`
    template<class T>
    decltype(static_cast<void>(*std::declval<T>()), std::true_type)
    can_be_dereferenced_impl(int);

    // Otherwise the less specific function is selected,
    // and the return type is `std::false_type`
    template<class>
    std::false_type can_be_dereferenced_impl(...);


    template<class T>
    struct can_be_dereferenced : decltype(detail::can_be_dereferenced_impl<T>(0)) ;

    template<class T>
    void func(T var)

    if constexpr (can_be_dereferenced<T&>::value)
    // Or can_be_dereferenced<decltype((var))>::value

    auto&& dereferenced = *var;
    // Use dereferenced







    share|improve this answer

























    • This is exactly what I needed. Thanks a lot!

      – dinpin
      Mar 27 at 13:42















    3














    You basically want to check if *var is valid. This is the perfect use case for a SFINAE check:



    #include <type_traits>
    #include <utility>

    namespace detail
    // If `*(object of type T)` is valid, this is selected and
    // the return type is `std::true_type`
    template<class T>
    decltype(static_cast<void>(*std::declval<T>()), std::true_type)
    can_be_dereferenced_impl(int);

    // Otherwise the less specific function is selected,
    // and the return type is `std::false_type`
    template<class>
    std::false_type can_be_dereferenced_impl(...);


    template<class T>
    struct can_be_dereferenced : decltype(detail::can_be_dereferenced_impl<T>(0)) ;

    template<class T>
    void func(T var)

    if constexpr (can_be_dereferenced<T&>::value)
    // Or can_be_dereferenced<decltype((var))>::value

    auto&& dereferenced = *var;
    // Use dereferenced







    share|improve this answer

























    • This is exactly what I needed. Thanks a lot!

      – dinpin
      Mar 27 at 13:42













    3












    3








    3







    You basically want to check if *var is valid. This is the perfect use case for a SFINAE check:



    #include <type_traits>
    #include <utility>

    namespace detail
    // If `*(object of type T)` is valid, this is selected and
    // the return type is `std::true_type`
    template<class T>
    decltype(static_cast<void>(*std::declval<T>()), std::true_type)
    can_be_dereferenced_impl(int);

    // Otherwise the less specific function is selected,
    // and the return type is `std::false_type`
    template<class>
    std::false_type can_be_dereferenced_impl(...);


    template<class T>
    struct can_be_dereferenced : decltype(detail::can_be_dereferenced_impl<T>(0)) ;

    template<class T>
    void func(T var)

    if constexpr (can_be_dereferenced<T&>::value)
    // Or can_be_dereferenced<decltype((var))>::value

    auto&& dereferenced = *var;
    // Use dereferenced







    share|improve this answer













    You basically want to check if *var is valid. This is the perfect use case for a SFINAE check:



    #include <type_traits>
    #include <utility>

    namespace detail
    // If `*(object of type T)` is valid, this is selected and
    // the return type is `std::true_type`
    template<class T>
    decltype(static_cast<void>(*std::declval<T>()), std::true_type)
    can_be_dereferenced_impl(int);

    // Otherwise the less specific function is selected,
    // and the return type is `std::false_type`
    template<class>
    std::false_type can_be_dereferenced_impl(...);


    template<class T>
    struct can_be_dereferenced : decltype(detail::can_be_dereferenced_impl<T>(0)) ;

    template<class T>
    void func(T var)

    if constexpr (can_be_dereferenced<T&>::value)
    // Or can_be_dereferenced<decltype((var))>::value

    auto&& dereferenced = *var;
    // Use dereferenced








    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 27 at 12:57









    ArtyerArtyer

    7,7511 gold badge12 silver badges33 bronze badges




    7,7511 gold badge12 silver badges33 bronze badges















    • This is exactly what I needed. Thanks a lot!

      – dinpin
      Mar 27 at 13:42

















    • This is exactly what I needed. Thanks a lot!

      – dinpin
      Mar 27 at 13:42
















    This is exactly what I needed. Thanks a lot!

    – dinpin
    Mar 27 at 13:42





    This is exactly what I needed. Thanks a lot!

    – dinpin
    Mar 27 at 13:42













    0














    You might do it in this way using compile time function overload resolution and SFINAE:



    template<class T, typename = std::enable_if_t<std::is_pointer<T>::value>>
    void func(T var)

    // a pointer


    template<class T, typename = std::enable_if_t<!std::is_pointer<T>::value>,
    typename = T::value_type>
    void func(T var)

    // possibly an iterator


    int main()
    {
    int *i = new int(11);
    func(i); // Calls the first overload

    std::vector<int> v;
    std::vector<int>::const_iterator it = v.begin();

    func(it); // Calls the second overload

    func(2); // Fail, as there is no function for this argument.
    [..]





    share|improve this answer





























      0














      You might do it in this way using compile time function overload resolution and SFINAE:



      template<class T, typename = std::enable_if_t<std::is_pointer<T>::value>>
      void func(T var)

      // a pointer


      template<class T, typename = std::enable_if_t<!std::is_pointer<T>::value>,
      typename = T::value_type>
      void func(T var)

      // possibly an iterator


      int main()
      {
      int *i = new int(11);
      func(i); // Calls the first overload

      std::vector<int> v;
      std::vector<int>::const_iterator it = v.begin();

      func(it); // Calls the second overload

      func(2); // Fail, as there is no function for this argument.
      [..]





      share|improve this answer



























        0












        0








        0







        You might do it in this way using compile time function overload resolution and SFINAE:



        template<class T, typename = std::enable_if_t<std::is_pointer<T>::value>>
        void func(T var)

        // a pointer


        template<class T, typename = std::enable_if_t<!std::is_pointer<T>::value>,
        typename = T::value_type>
        void func(T var)

        // possibly an iterator


        int main()
        {
        int *i = new int(11);
        func(i); // Calls the first overload

        std::vector<int> v;
        std::vector<int>::const_iterator it = v.begin();

        func(it); // Calls the second overload

        func(2); // Fail, as there is no function for this argument.
        [..]





        share|improve this answer













        You might do it in this way using compile time function overload resolution and SFINAE:



        template<class T, typename = std::enable_if_t<std::is_pointer<T>::value>>
        void func(T var)

        // a pointer


        template<class T, typename = std::enable_if_t<!std::is_pointer<T>::value>,
        typename = T::value_type>
        void func(T var)

        // possibly an iterator


        int main()
        {
        int *i = new int(11);
        func(i); // Calls the first overload

        std::vector<int> v;
        std::vector<int>::const_iterator it = v.begin();

        func(it); // Calls the second overload

        func(2); // Fail, as there is no function for this argument.
        [..]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 12:56









        vahanchovahancho

        16.4k3 gold badges27 silver badges35 bronze badges




        16.4k3 gold badges27 silver badges35 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55377316%2fhow-to-check-whether-variable-of-given-type-can-be-dereferenced%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현