C ++ template type calculation

I have this code:

template <typename T, void (*f)(T*)>
class callfn
{
  public:
  void operator()(T* obj) const
  {
    f(obj);
  }
};

void call(int* foo) {}

void test()
{
  callfn<int, call> fun;
  fun(1);
}

It usually works fine. the type callfn, however, is used everywhere, and I would prefer that I can call it that way

callfn<call> fun;

instead, without changing the type callIs it possible to organize the template / templates callfnso that it can infer the type Tfrom the type f?

+4
source share
2 answers

No, you need to know the arguments for a struct or class function, only functions have a template type subtraction in C ++.

n3602, , , , , ( ). , , , . n6301 , -.

( ++ 14) - make_unique, . , , .

, , , .

, , deleter unique_ptr, , .

std::unique_ptr<int,void(*)(int*)> ptr(int_ptr,deleter);
+1

aaronman post. , , , :

template <typename T>
T deduce(void(*)(T*));

#define CALLFN(f) callfn<decltype(deduce(f)), f> 

:

CALLFN(call) fun; // instead of 'callfn<call> fun;' as asked

OP , .

, std::unique_ptr T f ( void (*)(T*)), , std::unique_ptr. , :

class MObj { /* ... */ };
void mfree(MObj*) { /* ... */ }

OP,

std::unique_ptr<MObj, void(*)(MObj*)> p1(nullptr, mfree);
assert(sizeof(p1) == sizeof(MObj*) * 2);

callfn, :

std::unique_ptr<MObj, callfn<MObj, mfree>> p2;
assert(sizeof(p2) == sizeof(MObj*));

, - callfn MObj . , :

template <typename T, void (*f)(T*)>
using light_unique_ptr = std::unique_ptr<T, callfn<T, f>>;

light_unique_ptr<MObj, mfree> p3; // 1
assert(sizeof(p3) == sizeof(MObj*));

( , ), - ,

lighter_unique_ptr<mfree> p4; // 2
assert(sizeof(p4) == sizeof(MObj*));

mfree. , , , :

  • , mfree ( void mfree(MObj*) void mfree(Foo*)).
  • std::unique_ptr ( ) . 1 (MObj), 2 . , .

, ( , I-use-auto).

+2

All Articles