views:

140

answers:

1

I was trying use a set of filter functions to run the appropriate routine, based on a string input. I tried to create matcher functions for common cases using templates, but I get a "type not equal to type" error when I try to store a pointer to the specialized function (in a structure, in the real application)

Distilled example from a Visual C++ 8 'console application'

template <const char *C>
const char*
f(void) {
  return C;
}

const char* (*g)(void) = f<"hi">;


int _tmain(int argc, _TCHAR* argv[])
{
  return g();
}

This fails with the error

Error   1 error C2440: 'initializing' : cannot convert from 'const char *(__cdecl *)(void)' to 'const char *(__cdecl *)(void)' c:\files\pointer.cpp 7

(It also has an error on the main return value, but that doesn't concern me here.)

The same example succedes if const char * is replaced with int.

+2  A: 

Strings as template-value parameters are prohibited by the ISO standard.

eduffy
Additional info: Template value parameters must be built-in integral types.
rlbond
That stinks. So does the error message ;^)
Justin Love
@Mr. Bond: But pointers are integral types. The problem with string literals is that two equivalent strings that reside in different compilation units may have different addresses, creating two different template instantiations.
eduffy
pointers are scalar types, but they aren't integral types. They are just another form of parameters that are allowed. References are allowed as template parameters too, and member pointers.
Johannes Schaub - litb