Reputation: 113
I have the code like this (it's simplified version, really code more complex):
class IFoo {
public:
template <typename T> T GetInc(T x) const { return x; }
};
class Foo : public IFoo {
public:
template <typename T> T GetInc(T x) const { return x + 1; }
};
class Bar : public IFoo {
public:
template <typename T> T GetInc(T x) const { return x + 2; }
};
void Print(const IFoo& foo) {
std::cout << foo.GetInc(1) << std::endl;
std::cout << foo.GetInc(3.14) << std::endl;
}
int main() {
Foo foo;
Print(foo);
Bar bar;
Print(bar);
return 0;
}
Obviously, it outputs the wrong thing. I can use CRTP here, but then I'll have to template the Print
function (which I don't want to do)
template <typename T> class IFoo {
public:
template <typename U> U GetInc(U x) const {
return static_cast<const T *>(this)->GetInc(x);
}
};
class Foo : public IFoo<Foo> {
public:
template <typename T> T GetInc(T x) const { return x + 1; }
};
class Bar : public IFoo<Bar> {
public:
template <typename T> T GetInc(T x) const { return x + 2; }
};
template <typename T> void Print(const IFoo<T> &foo) {
std::cout << foo.GetInc(1) << std::endl;
std::cout << foo.GetInc(3.14) << std::endl;
}
I don't want to do this, because there are many places where such a call is used and it will complicate it.
I also tried to use the NVI pattern, but I couldn't call the templated function from the base class.
What other solutions are there? Initially, the problem is to create an interface for a class with template functions
Thanks a lot!
Upvotes: 0
Views: 53