Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to make the compiler include functions from outer scopes when picking a candidate?

Consider this class and variadic member function:

class foo
{
public:
    template<class C, class... Cs>
    void add(C&& c, Cs&&... cs)
    {
        ...
        
        add(cs...);
    }
private:
    void add(){ }
};

Is there a way to place the empty add overload that terminates the recursion inside another scope? Please ignore whether or not this is generally a good idea, I am strictly asking for how one could do it, if at all. I would like to place it inside an impl namespace like so:

namespace impl
{
    void add() {}
}

class foo
{
public:
    template<class C, class... Cs>
    void add(C&& c, Cs&&... cs)
    {
        ...
        
        using namespace impl;
        add(cs...);
    }
};

But the above code does not work when instatiated. The compiler complains that it can’t find a matching function call for add when the parameter pack is empty.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to achieve this using some scope-hackery?

>Solution :

How about using if constexpr:

namespace impl { void add() {} }

class foo {
 public:
  template<class C, class... Cs>
  void add(C&& c, Cs&&... cs)
  {
    if constexpr (sizeof...(Cs) == 0)
      impl::add();
    else
      add(cs...);
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading