Template implementation for commutative operators, legal?2019 Community Moderator ElectionWhy can templates only be implemented in the header file?Where and why do I have to put the “template” and “typename” keywords?What is the “-->” operator in C++?What are the basic rules and idioms for operator overloading?Is a c++11 variadic function template overload with a dependent type ambiguous?Is it possible to use -1 to fetch the last element of a container/array?clarification of decltype output when multiplying 2 const intsImplementing is_constexpr_copiableClang can't find template binary operator in fold expressionError in template instantiation before overloading

Are babies of evil humanoid species inherently evil?

Difference on montgomery curve equation between EFD and RFC7748

Why does Captain Marvel assume the people on this planet know this?

UART pins to unpowered MCU?

Intuition behind counterexample of Euler's sum of powers conjecture

Is it "Vierergruppe" or "Viergruppe", or is there a distinction?

Single word request: Harming the benefactor

Signed and unsigned numbers

Is "history" a male-biased word ("his+story")?

meaning and function of 幸 in "则幸分我一杯羹"

What are actual Tesla M60 models used by AWS?

Declaring and defining template, and specialising them

How do I express some one as a black person?

Why does the negative sign arise in this thermodynamic relation?

Hotkey (or other quick way) to insert a keyframe for only one component of a vector-valued property?

Can Mathematica be used to create an Artistic 3D extrusion from a 2D image and wrap a line pattern around it?

Reverse string, can I make it faster?

How can I get players to stop ignoring or overlooking the plot hooks I'm giving them?

Conservation of Mass and Energy

Is it possible to avoid unpacking when merging Association?

How to detect if C code (which needs 'extern C') is compiled in C++

List elements digit difference sort

Dropdown com clique

Accountant/ lawyer will not return my call



Template implementation for commutative operators, legal?



2019 Community Moderator ElectionWhy can templates only be implemented in the header file?Where and why do I have to put the “template” and “typename” keywords?What is the “-->” operator in C++?What are the basic rules and idioms for operator overloading?Is a c++11 variadic function template overload with a dependent type ambiguous?Is it possible to use -1 to fetch the last element of a container/array?clarification of decltype output when multiplying 2 const intsImplementing is_constexpr_copiableClang can't find template binary operator in fold expressionError in template instantiation before overloading










4















I've tried to implement a commutative addition operator for one of my classes:



struct mytype

constexpr mytype(othertype const &);
constexpr mytype operator+(othertype const &rhs) const;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;



The idea is that anything accepted on the right hand side also becomes acceptable on the left hand side as long as the right hand side is a mytype.



This works fine with icc and Visual Studio, and goes into an endless recursion resolving the decltype on gcc and clang (terminated when the maximum template depth is reached).



I can see that the endless recursion might in fact be more correct, as explained in the bug report: the specialization is needed before overload resolution takes place (because it is an input to overload resolution).



On the other hand the commercial compilers somehow manage (whether by accident or on purpose is probably debatable).



What is the correct behavior here?



Is it possible to avoid specifying a full list of classes for which operator+ is supposed to be commutative?



Compilable example:



struct othertype ;

struct mytype

constexpr mytype() : value(1)
constexpr mytype(int v) : value(v)
constexpr mytype(othertype const &o) : value(2) // 1

constexpr mytype operator+(mytype const &rhs) const

return mytype(value + rhs.value);

constexpr mytype operator+(othertype const &rhs) const // 2

return mytype(value + 2);


int value;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;


void test()

constexpr mytype mine;
constexpr othertype other;

constexpr auto result = other + mine;

static_assert(result.value == 3);



The problem goes away when the conversion // 1 is removed, which isn't helpful in my use case. The separate addition operator // 2 is not sufficient to help resolve the decltype: overload resolution should have picked that up, but the problem happens before overload resolution.



The infinite recursion happens after specializing the template for T = othertype: converting othertype to mytype gives an addition expression with mytype on both sides, which again can be resolved through the template (even though a non-template exists).










share|improve this question



















  • 1





    How do you use this operator? Could you perhaps show us a Minimal, Complete, and Verifiable example that exhibits the problem you have? Even if we can't replicate the problem, it could be useful to see how you use it. And it could be very useful to see your implementation of the member overload, and what othertype is.

    – Some programmer dude
    Mar 7 at 6:43












  • By the way, do you really need to non-explicit conversion operator? What happens if you remove it or make it explicit?

    – Some programmer dude
    Mar 7 at 6:56











  • @Someprogrammerdude, this is part of a refactoring — mytype is supposed to replace othertype in the long run, so it needs to be convertible to allow gradually replacing instances without breaking the rest of the program.

    – Simon Richter
    Mar 7 at 7:05















4















I've tried to implement a commutative addition operator for one of my classes:



struct mytype

constexpr mytype(othertype const &);
constexpr mytype operator+(othertype const &rhs) const;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;



The idea is that anything accepted on the right hand side also becomes acceptable on the left hand side as long as the right hand side is a mytype.



This works fine with icc and Visual Studio, and goes into an endless recursion resolving the decltype on gcc and clang (terminated when the maximum template depth is reached).



I can see that the endless recursion might in fact be more correct, as explained in the bug report: the specialization is needed before overload resolution takes place (because it is an input to overload resolution).



On the other hand the commercial compilers somehow manage (whether by accident or on purpose is probably debatable).



What is the correct behavior here?



Is it possible to avoid specifying a full list of classes for which operator+ is supposed to be commutative?



Compilable example:



struct othertype ;

struct mytype

constexpr mytype() : value(1)
constexpr mytype(int v) : value(v)
constexpr mytype(othertype const &o) : value(2) // 1

constexpr mytype operator+(mytype const &rhs) const

return mytype(value + rhs.value);

constexpr mytype operator+(othertype const &rhs) const // 2

return mytype(value + 2);


int value;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;


void test()

constexpr mytype mine;
constexpr othertype other;

constexpr auto result = other + mine;

static_assert(result.value == 3);



The problem goes away when the conversion // 1 is removed, which isn't helpful in my use case. The separate addition operator // 2 is not sufficient to help resolve the decltype: overload resolution should have picked that up, but the problem happens before overload resolution.



The infinite recursion happens after specializing the template for T = othertype: converting othertype to mytype gives an addition expression with mytype on both sides, which again can be resolved through the template (even though a non-template exists).










share|improve this question



















  • 1





    How do you use this operator? Could you perhaps show us a Minimal, Complete, and Verifiable example that exhibits the problem you have? Even if we can't replicate the problem, it could be useful to see how you use it. And it could be very useful to see your implementation of the member overload, and what othertype is.

    – Some programmer dude
    Mar 7 at 6:43












  • By the way, do you really need to non-explicit conversion operator? What happens if you remove it or make it explicit?

    – Some programmer dude
    Mar 7 at 6:56











  • @Someprogrammerdude, this is part of a refactoring — mytype is supposed to replace othertype in the long run, so it needs to be convertible to allow gradually replacing instances without breaking the rest of the program.

    – Simon Richter
    Mar 7 at 7:05













4












4








4








I've tried to implement a commutative addition operator for one of my classes:



struct mytype

constexpr mytype(othertype const &);
constexpr mytype operator+(othertype const &rhs) const;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;



The idea is that anything accepted on the right hand side also becomes acceptable on the left hand side as long as the right hand side is a mytype.



This works fine with icc and Visual Studio, and goes into an endless recursion resolving the decltype on gcc and clang (terminated when the maximum template depth is reached).



I can see that the endless recursion might in fact be more correct, as explained in the bug report: the specialization is needed before overload resolution takes place (because it is an input to overload resolution).



On the other hand the commercial compilers somehow manage (whether by accident or on purpose is probably debatable).



What is the correct behavior here?



Is it possible to avoid specifying a full list of classes for which operator+ is supposed to be commutative?



Compilable example:



struct othertype ;

struct mytype

constexpr mytype() : value(1)
constexpr mytype(int v) : value(v)
constexpr mytype(othertype const &o) : value(2) // 1

constexpr mytype operator+(mytype const &rhs) const

return mytype(value + rhs.value);

constexpr mytype operator+(othertype const &rhs) const // 2

return mytype(value + 2);


int value;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;


void test()

constexpr mytype mine;
constexpr othertype other;

constexpr auto result = other + mine;

static_assert(result.value == 3);



The problem goes away when the conversion // 1 is removed, which isn't helpful in my use case. The separate addition operator // 2 is not sufficient to help resolve the decltype: overload resolution should have picked that up, but the problem happens before overload resolution.



The infinite recursion happens after specializing the template for T = othertype: converting othertype to mytype gives an addition expression with mytype on both sides, which again can be resolved through the template (even though a non-template exists).










share|improve this question
















I've tried to implement a commutative addition operator for one of my classes:



struct mytype

constexpr mytype(othertype const &);
constexpr mytype operator+(othertype const &rhs) const;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;



The idea is that anything accepted on the right hand side also becomes acceptable on the left hand side as long as the right hand side is a mytype.



This works fine with icc and Visual Studio, and goes into an endless recursion resolving the decltype on gcc and clang (terminated when the maximum template depth is reached).



I can see that the endless recursion might in fact be more correct, as explained in the bug report: the specialization is needed before overload resolution takes place (because it is an input to overload resolution).



On the other hand the commercial compilers somehow manage (whether by accident or on purpose is probably debatable).



What is the correct behavior here?



Is it possible to avoid specifying a full list of classes for which operator+ is supposed to be commutative?



Compilable example:



struct othertype ;

struct mytype

constexpr mytype() : value(1)
constexpr mytype(int v) : value(v)
constexpr mytype(othertype const &o) : value(2) // 1

constexpr mytype operator+(mytype const &rhs) const

return mytype(value + rhs.value);

constexpr mytype operator+(othertype const &rhs) const // 2

return mytype(value + 2);


int value;
;

template<typename T>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;


void test()

constexpr mytype mine;
constexpr othertype other;

constexpr auto result = other + mine;

static_assert(result.value == 3);



The problem goes away when the conversion // 1 is removed, which isn't helpful in my use case. The separate addition operator // 2 is not sufficient to help resolve the decltype: overload resolution should have picked that up, but the problem happens before overload resolution.



The infinite recursion happens after specializing the template for T = othertype: converting othertype to mytype gives an addition expression with mytype on both sides, which again can be resolved through the template (even though a non-template exists).







c++ c++11 language-lawyer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 7:04







Simon Richter

















asked Mar 7 at 6:37









Simon RichterSimon Richter

21.8k13352




21.8k13352







  • 1





    How do you use this operator? Could you perhaps show us a Minimal, Complete, and Verifiable example that exhibits the problem you have? Even if we can't replicate the problem, it could be useful to see how you use it. And it could be very useful to see your implementation of the member overload, and what othertype is.

    – Some programmer dude
    Mar 7 at 6:43












  • By the way, do you really need to non-explicit conversion operator? What happens if you remove it or make it explicit?

    – Some programmer dude
    Mar 7 at 6:56











  • @Someprogrammerdude, this is part of a refactoring — mytype is supposed to replace othertype in the long run, so it needs to be convertible to allow gradually replacing instances without breaking the rest of the program.

    – Simon Richter
    Mar 7 at 7:05












  • 1





    How do you use this operator? Could you perhaps show us a Minimal, Complete, and Verifiable example that exhibits the problem you have? Even if we can't replicate the problem, it could be useful to see how you use it. And it could be very useful to see your implementation of the member overload, and what othertype is.

    – Some programmer dude
    Mar 7 at 6:43












  • By the way, do you really need to non-explicit conversion operator? What happens if you remove it or make it explicit?

    – Some programmer dude
    Mar 7 at 6:56











  • @Someprogrammerdude, this is part of a refactoring — mytype is supposed to replace othertype in the long run, so it needs to be convertible to allow gradually replacing instances without breaking the rest of the program.

    – Simon Richter
    Mar 7 at 7:05







1




1





How do you use this operator? Could you perhaps show us a Minimal, Complete, and Verifiable example that exhibits the problem you have? Even if we can't replicate the problem, it could be useful to see how you use it. And it could be very useful to see your implementation of the member overload, and what othertype is.

– Some programmer dude
Mar 7 at 6:43






How do you use this operator? Could you perhaps show us a Minimal, Complete, and Verifiable example that exhibits the problem you have? Even if we can't replicate the problem, it could be useful to see how you use it. And it could be very useful to see your implementation of the member overload, and what othertype is.

– Some programmer dude
Mar 7 at 6:43














By the way, do you really need to non-explicit conversion operator? What happens if you remove it or make it explicit?

– Some programmer dude
Mar 7 at 6:56





By the way, do you really need to non-explicit conversion operator? What happens if you remove it or make it explicit?

– Some programmer dude
Mar 7 at 6:56













@Someprogrammerdude, this is part of a refactoring — mytype is supposed to replace othertype in the long run, so it needs to be convertible to allow gradually replacing instances without breaking the rest of the program.

– Simon Richter
Mar 7 at 7:05





@Someprogrammerdude, this is part of a refactoring — mytype is supposed to replace othertype in the long run, so it needs to be convertible to allow gradually replacing instances without breaking the rest of the program.

– Simon Richter
Mar 7 at 7:05












1 Answer
1






active

oldest

votes


















1














You might restrict your template with SFINAE to discard operator+<mytype>(mytype const &lhs, mytype const &rhs):



template<typename T, typename std::enable_if<!std::is_same<T, mytype>::value, int>::type = 0>
constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

return rhs + lhs;



Demo






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%2f55037500%2ftemplate-implementation-for-commutative-operators-legal%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









    1














    You might restrict your template with SFINAE to discard operator+<mytype>(mytype const &lhs, mytype const &rhs):



    template<typename T, typename std::enable_if<!std::is_same<T, mytype>::value, int>::type = 0>
    constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

    return rhs + lhs;



    Demo






    share|improve this answer



























      1














      You might restrict your template with SFINAE to discard operator+<mytype>(mytype const &lhs, mytype const &rhs):



      template<typename T, typename std::enable_if<!std::is_same<T, mytype>::value, int>::type = 0>
      constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

      return rhs + lhs;



      Demo






      share|improve this answer

























        1












        1








        1







        You might restrict your template with SFINAE to discard operator+<mytype>(mytype const &lhs, mytype const &rhs):



        template<typename T, typename std::enable_if<!std::is_same<T, mytype>::value, int>::type = 0>
        constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

        return rhs + lhs;



        Demo






        share|improve this answer













        You might restrict your template with SFINAE to discard operator+<mytype>(mytype const &lhs, mytype const &rhs):



        template<typename T, typename std::enable_if<!std::is_same<T, mytype>::value, int>::type = 0>
        constexpr auto operator+(T const &lhs, mytype const &rhs) -> decltype(rhs + lhs)

        return rhs + lhs;



        Demo







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 9:55









        Jarod42Jarod42

        118k12103189




        118k12103189





























            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%2f55037500%2ftemplate-implementation-for-commutative-operators-legal%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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page