2

Is it possible to define an interface such as:

class IFoo
{
  virtual void foo(const X &x) const = 0;
  virtual void foo(X &x) = 0;
};

and define both foo methods in a subclass C with a template which can be instantiated twice, once for type argument <const X> and once for <X>? e.g something like:

class C : public IFoo
{
  template<typename T>
  void foo(T &t) {...}
};

// instantiate void C::foo(X &x)
//         and void C::foo(const X &x) const ???
fferri
  • 15,633
  • 3
  • 36
  • 67
  • 2
    Not directly, but if the template has a different name, then the implementation can implement the overrides with a single line each. – Mooing Duck Jul 17 '18 at 21:54
  • If you only have const and non-const, see: https://stackoverflow.com/q/123758/1896169 – Justin Jul 17 '18 at 21:58
  • Somewhat unusual way of dealing with such issues: if methods seems to be identical except for `const` qualifiers they are actually fundamentally different. That is they deserve different names and separate independent implementations. Even if their implementations happen to be identical it would be just a coincidence. – user7860670 Jul 17 '18 at 22:13

2 Answers2

2

Template functions cannot be virtual, so even if you were able to apply const-ness according to the template parameter, you would not be overriding the virtual functions. For example, the following fails to compile on g++ (4.8.5) with: error: templates may not be ‘virtual’

#include <iostream>

class IFoo
{
  virtual void foo(int &x) = 0;
};

class C : public IFoo
{
  template<typename T>
  virtual void foo(T &t) override {
    std::cout << "foo" << std::endl;
  }
};

int main() {
  C c;
  c.foo(1);
  return 0;
}
eightdatabits
  • 21
  • 1
  • 3
-1

As far as I know, it isn't possible. C++ allows to specify noexcept with additional compile time bool conditional, but this is sadly not true for const. Having an option to specify

template<typename T>
void foo(T &t) const(std::is_const_v<T>)
{
}

would be nice.

Zereges
  • 4,833
  • 1
  • 20
  • 47