Reputation: 3194
Is it possible to define the typecast operator as a non-member global function?
#include <stdio.h>
#include <stdlib.h>
typedef int hash_t;
struct wrap {
int v;
operator hash_t () {
hash_t h = v+1;
return h;
}
};
int main(int argc, char **argv) {
int v = 1;
hash_t h = (hash_t)wrap{v};
printf("%d\n", h);
return 0;
}
Instead of (hash_t)wrap{v}
being able to write (hash_t)v
would be helpful. Not shure how the syntax of the overload would be, but something like operator hash_t (int v) { ... }
? Or is the typecast operator only overloadable in with memberfunction of a class/struct?
I want to define a dictionary template <typename key> CDict
and want to convert key to int to use it as a hash. But I dont want to dispatch the hash function depending on the type of key or use a virtual function and also be able to use int as type for key.... Instead I want to overload the (hash_t) typecast.
Is this possible with global typecast overloads (or dont they exits) ?
Upvotes: 1
Views: 160
Reputation: 36792
It seems what you actually want to do is call different functions depending on the type, the operator overload is not the right way to go about this.
Instead, you can create a free function to handle int
specifically, and then delegate to a member function in the non-int case
using hash_type = int;
// handle int
hash_type my_hash(int i) {
return i;
}
// handle anything else
template <typename T>
hash_type my_hash(const T& t) {
return t.hash(); // use whatever pattern you want here
}
template <typename Key, typename Value>
struct CDict {
void insert(const Key& k, const Value& v) {
auto hash = my_hash(k); // calls correct overload
}
};
// a type with a hash member function
struct MyHashable {
hash_type hash() const {
return 0;
}
};
int main() {
CDict<int, double> c1;
c1.insert(3, 5.0);
CDict<MyHashable, char> c2;
c2.insert(MyHashable{}, 'a');
}
Don't create type names ending with _t
, they are reserved
Upvotes: 1