M
M
maxwolf2014-07-30 19:16:13
C++ / C#
maxwolf, 2014-07-30 19:16:13

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) {};
}

Is it possible to describe a function that, depending on the template argument, would call the f1() or f2() method?
Something like this:
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

3 answer(s)
J
jcmvbkbc, 2014-07-31
@jcmvbkbc

Is it possible to describe a function that, depending on the template argument, would call the f1() or f2() method?

Here is an option with specialization and without additional parameters in the signature:
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);
}

T
tugo, 2014-07-30
@tugo

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;
}

cpp.sh/3l5

B
bogolt, 2014-07-30
@bogolt

You cannot pass a function name as an argument.
You can solve this through macros, for example like this . You
can also pass a pointer to a function, but I think it will be a little more gemorno.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question