Templates and Function Pointers

Really scratching my head on this one;

Brief
Trying to get this code to compile; It fails when I try to call the instance method on the object, for some reason it takes the function pointer as literal rather than the parameter.

Code Sample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "stdafx.h"
#include<iostream>
#include<cstdlib>

// uses macro for easy usage ie;- PROFILE_METHOD(instanceType, methodOffset)(instancePtr, someText);
template<class T, typename Fn, Fn fn>
void
timeFunc(T t, std::string opTitle)
{
	// ...
	(t)->fn(); // how to make this work??
	// ...
}
#define PROFILE_METHOD(INST, FUNC) timeFunc<INST, decltype(&FUNC), &FUNC>

// Class being tested
struct classToTest
{
	void testMethod1()
	{
		std::cout << "classToTest::testMethod1()" << std::endl;
	}
};

// class that is testing
struct ClassRunningTest
{
	classToTest * tc{ new classToTest()};
	void testClass()
	{
		// Use profile func to test method
		PROFILE_METHOD(classToTest*, classToTest::testMethod1)(tc, "some title ");

	}
};

int main()
{
	// try test
	ClassRunningTest * test1 = new ClassRunningTest();
	test1->testClass();

	return 0;
}


Error
line:
(t)->fn();

Text:
C2039 'fn': is not a member of 'classToTest'

Compiler:
MSVC Pro 2015 Update 1

Operating Sys:
Windows 7 64bit Core i5


End Goal
To be able to pass any instanced class method (with no arguments or return type), to this function, inside the function do some calculations/timing while executing the method. I'm just fiddling with making a rudimentary performance profiler I can quickly bash with, I know there are tools and libs, I would still like to know the answer though).

Thanks!

Last edited on
You do not have a function pointer. You have a pointer-to-member-function, which is an entirely different thing with an entirely different syntax.

Instead, you should get rid of that macro and just use std::bind to pre-bundle the this pointer - then your function can act on any kind of function and not just class member functions.

http://www.cplusplus.com/reference/functional/bind/
http://en.cppreference.com/w/cpp/utility/functional/bind
Last edited on
Topic archived. No new replies allowed.