---
title: "funktionspekare"
type: "forum-thread"
url: "https://www.webforum.nu/amne/c-cpp/126449-funktionspekare"
topic: "C/C++"
topic_url: "https://www.webforum.nu/amne/c-cpp"
author: "MCW"
published: "2005-04-15T09:02:11.000Z"
updated: "2005-04-15T10:42:28.000Z"
replies: 2
views: 279
page: 1
pages: 1
language: "sv-SE"
site: "webForum — webforum.nu"
rights: "Upphovsrätten till varje inlägg tillhör dess författare."
attribution: "Citera som: webForum, https://www.webforum.nu/amne/c-cpp/126449-funktionspekare"
---

# funktionspekare

## #1 — MCW, 2005-04-15T09:02Z

Följande kompilerar fint. Men jag kan inte ta bort kommenteringen i do_action. Då klagar den på att function() vill ha ett annat antal argument (foo och bar är olika!). På vilket sätt kan jag lösa detta? Det viktigaste är att koden i main() är ser ut så här.

```
# include <iostream>

class A
{
 public:
  virtual ~A() {};
  virtual bool do_action() = 0;
};

template<class F, class T1, class T2 = int>
class B : public A
{
 public:
  B(F fcn, T1 arg1) 
    : function(fcn), argument1(arg1) {};

  B(F fcn, T1 arg1, T2 arg2) 
    : function(fcn), argument1(arg1), argument2(arg2) {};

  ~B() {};

  bool do_action() {
    //function(argument1);  
    //function(argument1,argument2);
    return true;
  }
  
  F function;
  T1 argument1;
  T2 argument2;
};

void foo(int i) {
  std::cout << "foo(" << i << ")\n";
}

void bar(int i, int j) {
  std::cout << "bar(" << i << "," << j << ")\n";
}

int main() {
  
  B<void (*)(int),int> b1(&foo,1);
  b1.do_action();
  
  B<void (*)(int,int),int,int> b2(&bar,2,2);
  b2.do_action();
  
  return 0;
}
```

Permalänk: https://www.webforum.nu/p/126449

## #2 — pimme, 2005-04-15T10:32Z

Om jag inte minns helt fel så ska du inte ha & före foo, dvs du ska ha
B\<void (\*)(int),int\> b1(foo,1);
B\<void (\*)(int,int),int,int\> b2(bar,2,2);

Jag är inte säker, men du kan ju testa.

Permalänk: https://www.webforum.nu/p/1592439

## #3 — MCW, 2005-04-15T10:42Z

Det går det också, men det löser inte mitt problem. Jag vill ha något liknande med detta (fast det kompilerar inte). Taget från klassdefinitionen av B.

```
 B(F fcn, T1 arg1) 
    : function(fcn), argument1(arg1), n(1) {};

  B(F fcn, T1 arg1, T2 arg2) 
    : function(fcn), argument1(arg1), argument2(arg2), n(2) {};

  ~B() {};

  bool do_action() {
    if (n==1) function(argument1);  
    if (n==2) function(argument1,argument2);
    return true;
  }
```

Permalänk: https://www.webforum.nu/p/1592447

---

Tråden på webben: https://www.webforum.nu/amne/c-cpp/126449-funktionspekare
