【发布时间】:2020-09-10 15:22:41
【问题描述】:
我正在编写一个模板化的哈希图。 如果模板类型是基本类型,我希望通过引用传递函数声明。
例如使用以下声明:
template<typename K,
typename V,
typename Hasher = DEFAULT_HASH_32<K>,
typename Allocator = DEFAULT_MMAP_ALLOC<K, V>>
class my_table {
...
int add(K const & key, V const & val);
};
...
template<typename K, typename V, typename Hasher, typename Allocator>
int
my_table<K, V, Hasher, Allocator>::add(K const & key, V const & val)
我希望能够在传递 K 或 V 作为参考或作为值之间切换,具体取决于给定类型的最佳值。
我知道我可以拥有 int add(...) 函数的副本,但我想知道是否有一种方法可以只更改声明而不必拥有完全相同的函数的副本。
显然下面的伪代码不起作用,但它应该清楚地说明我正在尝试做什么:
#if is_fundemental<K> && is_fundemental<V>
int add(K key, V val);
#elif is_fundemental<K> && !is_fundemental<V>
int add(K key, V const & val);
#elif !is_fundemental<K> && is_fundemental<V>
int add(K const & key, V val);
#else
int add(K const & key, V const & val);
#endif
// then at the functions implementation
#if is_fundemental<K> && is_fundemental<V>
int add(K key, V val) {
#elif is_fundemental<K> && !is_fundemental<V>
int add(K key, V const & val) {
#elif !is_fundemental<K> && is_fundemental<V>
int add(K const & key, V val) {
#else
int add(K const & key, V const & val) {
#endif
谢谢!
编辑:Piotr Skotnicki 有答案!
【问题讨论】: