使用enable_if在按值传递与按引用传递之间更改函数声明

问题描述 投票:0回答:1

我正在编写模板化的哈希图。因为如果模板类型是基本类型,我希望函数声明通过引用传递。

例如,带有以下声明:

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

谢谢!

c++ enable-if
1个回答
0
投票
#include <type_traits>

template <typename K, typename V>
class my_table
{
    template <typename T>
    using param_type = std::conditional_t<std::is_fundamental_v<T>, T, const T&>;

public:
    int add(param_type<K> key, param_type<V> val);
};

template <typename K, typename V>
int my_table<K, V>::add(param_type<K> key, param_type<V> val)
{
    return {};
}

DEMO

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.