Detecting existence of a class memberStatic class member destruction in C++Elementwise perfect forwarding of a member rangeDetecting cyclesClass member method based multithreading [C++]Small coroutine classUsing shared_ptr as class memberCallback class to callback member (virtual) functionsAn iterator wrapper that on dereferencing, returns the value of a member (function)product member of CSC matrix classC++ Class for optionally constructing arbitrary derived classes

If you inherit a Roth 401(k), is it taxed?

What language is Raven using for her attack in the new 52?

Why is it considered acid rain with pH <5.6?

Why does aggregate initialization not work anymore since C++20 if a constructor is explicitly defaulted or deleted?

Surviving a planet collision?

Rampant sharing of authorship among colleagues in the name of "collaboration". Is not taking part in it a death knell for a future in academia?

A variant of the Multiple Traveling Salesman Problem

Is SecureRandom.ints() secure?

Can this party play the Lost Mine of Phandelver adventure without too much trouble?

A cubeful of three-dimensional devilry

Shouldn't there be "us" instead of "our" in this sentence?

What force enables us to walk? Friction or normal reaction?

Why force the nose of 737 Max down in the first place?

How can Paypal know my card is being used in another account?

Why is it "on the inside" and not "in the inside"?

Is it safe if the neutral lead is exposed and disconnected?

GNU sort stable sort when sort does not know sort order

Is there a word to describe someone who is, or the state of being, content with hanging around others without interacting with them?

Convert graph format for Mathematica graph functions

Can Lightning Lure be used to knock out a creature like a magical Taser?

Piece of chess engine, which accomplishes move generation

Was Donald Trump at ground zero helping out on 9-11?

Why does the Eurostar not show youth pricing?

Why did Windows 95 crash the whole system but newer Windows only crashed programs?



Detecting existence of a class member


Static class member destruction in C++Elementwise perfect forwarding of a member rangeDetecting cyclesClass member method based multithreading [C++]Small coroutine classUsing shared_ptr as class memberCallback class to callback member (virtual) functionsAn iterator wrapper that on dereferencing, returns the value of a member (function)product member of CSC matrix classC++ Class for optionally constructing arbitrary derived classes






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








8












$begingroup$


I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:



#include <iostream>

template<class...Fs>
struct funcs_t;

template<class F0, class...Fs>
struct funcs_t<F0, Fs...>: F0, funcs_t<Fs...>
funcs_t(F0 f0, Fs... fs):
F0(std::move(f0)), funcs_t<Fs...>(std::move(fs)...)

using F0::operator();
using funcs_t<Fs...>::operator();
;

template<class F>
struct funcs_t<F>:F
funcs_t(F f) : F(std::move(f)) ;
using F::operator();
;

template<class...Fs>
funcs_t<std::decay_t<Fs>...> funcs(Fs&&...fs)
return std::forward<Fs>(fs)...;


#define HAS_MEMBER(cls, memb)
[]()
auto with_memb = [](auto &&A, int x)
-> decltype(typename std::remove_reference<decltype(A)>::type().memb, std::true_type())

return std::true_type();
;
auto with_no_memb = [](auto &&A, float x) -> std::false_type
return std::false_type();
;
auto has_memb = funcs(with_memb, with_no_memb);
return has_memb(cls(), 1);
()

struct A
int a;
int b;
;

int main(int argc, char const *argv[])

std::cout << HAS_MEMBER(A, b) << std::endl;
return 0;










share|improve this question











$endgroup$









  • 1




    $begingroup$
    Why do you need this? What are you trying to achieve?
    $endgroup$
    – Martin York
    Jul 19 at 16:39










  • $begingroup$
    I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for.
    $endgroup$
    – Pangi
    Jul 19 at 18:45











  • $begingroup$
    Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change).
    $endgroup$
    – Mast
    Jul 19 at 19:04










  • $begingroup$
    Ok, I'll keep that in mind.
    $endgroup$
    – Pangi
    Jul 19 at 19:16

















8












$begingroup$


I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:



#include <iostream>

template<class...Fs>
struct funcs_t;

template<class F0, class...Fs>
struct funcs_t<F0, Fs...>: F0, funcs_t<Fs...>
funcs_t(F0 f0, Fs... fs):
F0(std::move(f0)), funcs_t<Fs...>(std::move(fs)...)

using F0::operator();
using funcs_t<Fs...>::operator();
;

template<class F>
struct funcs_t<F>:F
funcs_t(F f) : F(std::move(f)) ;
using F::operator();
;

template<class...Fs>
funcs_t<std::decay_t<Fs>...> funcs(Fs&&...fs)
return std::forward<Fs>(fs)...;


#define HAS_MEMBER(cls, memb)
[]()
auto with_memb = [](auto &&A, int x)
-> decltype(typename std::remove_reference<decltype(A)>::type().memb, std::true_type())

return std::true_type();
;
auto with_no_memb = [](auto &&A, float x) -> std::false_type
return std::false_type();
;
auto has_memb = funcs(with_memb, with_no_memb);
return has_memb(cls(), 1);
()

struct A
int a;
int b;
;

int main(int argc, char const *argv[])

std::cout << HAS_MEMBER(A, b) << std::endl;
return 0;










share|improve this question











$endgroup$









  • 1




    $begingroup$
    Why do you need this? What are you trying to achieve?
    $endgroup$
    – Martin York
    Jul 19 at 16:39










  • $begingroup$
    I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for.
    $endgroup$
    – Pangi
    Jul 19 at 18:45











  • $begingroup$
    Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change).
    $endgroup$
    – Mast
    Jul 19 at 19:04










  • $begingroup$
    Ok, I'll keep that in mind.
    $endgroup$
    – Pangi
    Jul 19 at 19:16













8












8








8


2



$begingroup$


I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:



#include <iostream>

template<class...Fs>
struct funcs_t;

template<class F0, class...Fs>
struct funcs_t<F0, Fs...>: F0, funcs_t<Fs...>
funcs_t(F0 f0, Fs... fs):
F0(std::move(f0)), funcs_t<Fs...>(std::move(fs)...)

using F0::operator();
using funcs_t<Fs...>::operator();
;

template<class F>
struct funcs_t<F>:F
funcs_t(F f) : F(std::move(f)) ;
using F::operator();
;

template<class...Fs>
funcs_t<std::decay_t<Fs>...> funcs(Fs&&...fs)
return std::forward<Fs>(fs)...;


#define HAS_MEMBER(cls, memb)
[]()
auto with_memb = [](auto &&A, int x)
-> decltype(typename std::remove_reference<decltype(A)>::type().memb, std::true_type())

return std::true_type();
;
auto with_no_memb = [](auto &&A, float x) -> std::false_type
return std::false_type();
;
auto has_memb = funcs(with_memb, with_no_memb);
return has_memb(cls(), 1);
()

struct A
int a;
int b;
;

int main(int argc, char const *argv[])

std::cout << HAS_MEMBER(A, b) << std::endl;
return 0;










share|improve this question











$endgroup$




I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:



#include <iostream>

template<class...Fs>
struct funcs_t;

template<class F0, class...Fs>
struct funcs_t<F0, Fs...>: F0, funcs_t<Fs...>
funcs_t(F0 f0, Fs... fs):
F0(std::move(f0)), funcs_t<Fs...>(std::move(fs)...)

using F0::operator();
using funcs_t<Fs...>::operator();
;

template<class F>
struct funcs_t<F>:F
funcs_t(F f) : F(std::move(f)) ;
using F::operator();
;

template<class...Fs>
funcs_t<std::decay_t<Fs>...> funcs(Fs&&...fs)
return std::forward<Fs>(fs)...;


#define HAS_MEMBER(cls, memb)
[]()
auto with_memb = [](auto &&A, int x)
-> decltype(typename std::remove_reference<decltype(A)>::type().memb, std::true_type())

return std::true_type();
;
auto with_no_memb = [](auto &&A, float x) -> std::false_type
return std::false_type();
;
auto has_memb = funcs(with_memb, with_no_memb);
return has_memb(cls(), 1);
()

struct A
int a;
int b;
;

int main(int argc, char const *argv[])

std::cout << HAS_MEMBER(A, b) << std::endl;
return 0;







c++ c++14 meta-programming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 19 at 19:04









Mast

7,8607 gold badges37 silver badges91 bronze badges




7,8607 gold badges37 silver badges91 bronze badges










asked Jul 19 at 8:26









PangiPangi

604 bronze badges




604 bronze badges










  • 1




    $begingroup$
    Why do you need this? What are you trying to achieve?
    $endgroup$
    – Martin York
    Jul 19 at 16:39










  • $begingroup$
    I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for.
    $endgroup$
    – Pangi
    Jul 19 at 18:45











  • $begingroup$
    Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change).
    $endgroup$
    – Mast
    Jul 19 at 19:04










  • $begingroup$
    Ok, I'll keep that in mind.
    $endgroup$
    – Pangi
    Jul 19 at 19:16












  • 1




    $begingroup$
    Why do you need this? What are you trying to achieve?
    $endgroup$
    – Martin York
    Jul 19 at 16:39










  • $begingroup$
    I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for.
    $endgroup$
    – Pangi
    Jul 19 at 18:45











  • $begingroup$
    Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change).
    $endgroup$
    – Mast
    Jul 19 at 19:04










  • $begingroup$
    Ok, I'll keep that in mind.
    $endgroup$
    – Pangi
    Jul 19 at 19:16







1




1




$begingroup$
Why do you need this? What are you trying to achieve?
$endgroup$
– Martin York
Jul 19 at 16:39




$begingroup$
Why do you need this? What are you trying to achieve?
$endgroup$
– Martin York
Jul 19 at 16:39












$begingroup$
I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for.
$endgroup$
– Pangi
Jul 19 at 18:45





$begingroup$
I have different pod structs with many common fields with the same meaning and I wanted to print them on screen. I will see if I can use it for other things but for now that's what I needed it for.
$endgroup$
– Pangi
Jul 19 at 18:45













$begingroup$
Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change).
$endgroup$
– Mast
Jul 19 at 19:04




$begingroup$
Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. If you want a fixed-version of your code to be available, post it as answer linking to Deduplicator's for credit (or post it as a new question, but it's hardly a major change).
$endgroup$
– Mast
Jul 19 at 19:04












$begingroup$
Ok, I'll keep that in mind.
$endgroup$
– Pangi
Jul 19 at 19:16




$begingroup$
Ok, I'll keep that in mind.
$endgroup$
– Pangi
Jul 19 at 19:16










1 Answer
1






active

oldest

votes


















6












$begingroup$


  1. Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.



    Anyway, pure existence is generally uninteresting, supported operations count.




  2. funcs() and funcs_t are nearly a generally useful abstraction.



    Just use perfect forwarding instead of by-value and std::move(). Allowing for all callables, including final classes, function-pointers, member-function-pointers, and the same wrapped in a std::reference_wrapper would admittedly add significant amounts of code.



    A good name would be overloaded.



  3. HAS_MEMBER needlessly depends on default-constructing the passed class. Fix that by using decltype, std::declval() and unevaluated contexts.


  4. If you don't use an argument, don't name it. Specifically for main(), just don't ask for it.


  5. Don't use std::endl. In the rare cases you actually need to flush manually, be explicit and use std::flush. Nearly always you are just crippling performance.


  6. return 0; is implicit for main(). Make of that what you will.






share|improve this answer











$endgroup$

















    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: "196"
    ;
    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: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2fcodereview.stackexchange.com%2fquestions%2f224463%2fdetecting-existence-of-a-class-member%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6












    $begingroup$


    1. Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.



      Anyway, pure existence is generally uninteresting, supported operations count.




    2. funcs() and funcs_t are nearly a generally useful abstraction.



      Just use perfect forwarding instead of by-value and std::move(). Allowing for all callables, including final classes, function-pointers, member-function-pointers, and the same wrapped in a std::reference_wrapper would admittedly add significant amounts of code.



      A good name would be overloaded.



    3. HAS_MEMBER needlessly depends on default-constructing the passed class. Fix that by using decltype, std::declval() and unevaluated contexts.


    4. If you don't use an argument, don't name it. Specifically for main(), just don't ask for it.


    5. Don't use std::endl. In the rare cases you actually need to flush manually, be explicit and use std::flush. Nearly always you are just crippling performance.


    6. return 0; is implicit for main(). Make of that what you will.






    share|improve this answer











    $endgroup$



















      6












      $begingroup$


      1. Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.



        Anyway, pure existence is generally uninteresting, supported operations count.




      2. funcs() and funcs_t are nearly a generally useful abstraction.



        Just use perfect forwarding instead of by-value and std::move(). Allowing for all callables, including final classes, function-pointers, member-function-pointers, and the same wrapped in a std::reference_wrapper would admittedly add significant amounts of code.



        A good name would be overloaded.



      3. HAS_MEMBER needlessly depends on default-constructing the passed class. Fix that by using decltype, std::declval() and unevaluated contexts.


      4. If you don't use an argument, don't name it. Specifically for main(), just don't ask for it.


      5. Don't use std::endl. In the rare cases you actually need to flush manually, be explicit and use std::flush. Nearly always you are just crippling performance.


      6. return 0; is implicit for main(). Make of that what you will.






      share|improve this answer











      $endgroup$

















        6












        6








        6





        $begingroup$


        1. Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.



          Anyway, pure existence is generally uninteresting, supported operations count.




        2. funcs() and funcs_t are nearly a generally useful abstraction.



          Just use perfect forwarding instead of by-value and std::move(). Allowing for all callables, including final classes, function-pointers, member-function-pointers, and the same wrapped in a std::reference_wrapper would admittedly add significant amounts of code.



          A good name would be overloaded.



        3. HAS_MEMBER needlessly depends on default-constructing the passed class. Fix that by using decltype, std::declval() and unevaluated contexts.


        4. If you don't use an argument, don't name it. Specifically for main(), just don't ask for it.


        5. Don't use std::endl. In the rare cases you actually need to flush manually, be explicit and use std::flush. Nearly always you are just crippling performance.


        6. return 0; is implicit for main(). Make of that what you will.






        share|improve this answer











        $endgroup$




        1. Your detector fails in the face of overloading and templating. Also, it will only detect (static) member-variables and (static) member-functions. While you can extend it to types (and type-aliases), accepting templates and overloading would need better language-provided reflection-facilities.



          Anyway, pure existence is generally uninteresting, supported operations count.




        2. funcs() and funcs_t are nearly a generally useful abstraction.



          Just use perfect forwarding instead of by-value and std::move(). Allowing for all callables, including final classes, function-pointers, member-function-pointers, and the same wrapped in a std::reference_wrapper would admittedly add significant amounts of code.



          A good name would be overloaded.



        3. HAS_MEMBER needlessly depends on default-constructing the passed class. Fix that by using decltype, std::declval() and unevaluated contexts.


        4. If you don't use an argument, don't name it. Specifically for main(), just don't ask for it.


        5. Don't use std::endl. In the rare cases you actually need to flush manually, be explicit and use std::flush. Nearly always you are just crippling performance.


        6. return 0; is implicit for main(). Make of that what you will.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 19 at 16:54

























        answered Jul 19 at 9:18









        DeduplicatorDeduplicator

        13.3k20 silver badges55 bronze badges




        13.3k20 silver badges55 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • 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.

            Use MathJax to format equations. MathJax reference.


            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%2fcodereview.stackexchange.com%2fquestions%2f224463%2fdetecting-existence-of-a-class-member%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

            Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

            Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

            Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림