I am targeting c++11 (with g++ version 4.7) and c++0x (with icpc 12.something, the intel c++ compiler). I might use clang some day.
I have the following data structure:
template<typename mydata_t>
struct mystruct {
template<typename mycmp_t,
int (*cmp)(const mydata_t &, const mycmp_t &)
>
void insert(const mydata_t &value, const mycmp_t &key) {
// use key to search for where to put value, by calling
// cmp(item_already_in_mystruct, key);
}
};
The idea is that the client could do
int double_double_compare_fun(const double &d1, const double &d2) { ...; }
int double_int_compare_fun(const double &d, const int &i) { ...; }
int main(void) {
struct mystruct<double> s;
s.insert<double, double_double_compare_fun>(4.2, 4.2);
s.insert<int, double_int_compare_fun>(6.2, 6);
}
or something less silly.
I currently have this working and it's not too crazy. But I'm hoping I can do better.
double_double_compare_fun
and double_int_compare_fun
already name the type of the second parameter. So in my head, I imagine there's some way to get the compiler to infer the first template argument to insert
. I'd love to be able to say
s.insert<double_double_compare_fun>(4.2, 4.2);
s.insert<double_int_compare_fun>(6.2, 6);
and have mycmp_t
inferred either from the signature of cmp
or from the type of key
. Alternatively, I'd be happy if mycmp_t
could default to the type of the second parameter to cmp
.
I tried variations on this theme and they didn't work, but hopefully it gives some intuition:
template<template<typename mycmp_t>
int (*cmp)(const mydata_t &, const mycmp_t &)
>
void insert(const mydata_t &value, const mycmp_t &key);
(gives me expected 'class' before '(' token, expected identifier before '(' token, expected '>' before '(' token
). I also imagined using a template like template<int (*cmp)(const mydata_t &, const mycmp_t &), typename mycmp_t>
but it says the mycmp_t
present in the signature isn't defined (yet) and things like that.