Answer the question
In order to leave comments, you need to log in
Is it possible to describe template from a class method?
Schematically, the task looks like this: there is a class, for example, this
class A {
public:
char *f1(int v) {};
char *f2(int v) {};
}
template <???fname???>
int F(A *a, int b) {
return a->fname(b);
}
Answer the question
In order to leave comments, you need to log in
Is it possible to describe a function that, depending on the template argument, would call the f1() or f2() method?
template <int f>
int F(A *a, int b) {
abort();
}
template<>
int F<1>(A *a, int b) {
return a->f1(b);
}
template<>
int F<2>(A *a, int b) {
return a->f2(b);
}
You can pass a pointer to a class method into a template.
#include <iostream> // std::cout
struct A
{
int f1(int v) {return v * 5;}
int f2(int v) {return v * 10;}
};
template <typename Foo>
int F(int b, A * a, Foo foo)
{
return (a->*foo)(b);
}
int main ()
{
A * a = new A;
std::cout << F(5, a, &A::f1) << '\n';
std::cout << F(10, a, &A::f2) << '\n';
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question