gpt4 book ai didi

c++ - 从参数包中删除最后一个参数

转载 作者:太空狗 更新时间:2023-10-29 20:40:09 26 4
gpt4 key购买 nike

今天,当第一百次使用相同的模板时,我想到了引入一个简单的替换。

代替

 QHash<int,QHash<int,QHash<int,int> > >

现在应该是:

 MultiKeyHash<int,int,int,int>

(不要与 QT 的 QMultiHash 类混淆)。

而前三个参数是键的类型,最后一个参数是值的类型。

 MultiKeyHash<TKey1,TKey2,....,TKeyN,TValue>

我目前的实现是这样的:

template <typename... Args>
struct MultiKeyHash;

template <typename TKey1, typename... Args>
struct MultiKeyHash<TKey1, Args...> : QHash<TKey1,MultiKeyHash<Args...> > {

typedef typename MultiKeyHash<Args...>::ValueType ValueType;
const ValueType& value(const TKey1 &key1, const Args_Without_Last&... args) const {
return operator[](key1).value(args...);
}
};

template <typename TKeyN, typename TValue>
struct MultiKeyHash<TKeyN,TValue> : QHash<TKeyN,TValue> {
typedef TValue ValueType;
};

一切都按预期工作,直到我想添加“值”方法。我当然不能使用“Args”作为第二个参数(-pack)的类型。我是否必须为它制作一个函数模板,或者有什么办法吗?

我必须如何定义“值”方法才能像这样调用它:

value(key1,key2,...,keyn)

最佳答案

这是 MultiHashKey 的工作版本。它使用 QHash 的虚拟实现来进行测试。

#include <iostream>

// Dummy implementation of QHash for testing purposes.
template <typename TKey, typename TValue>
struct QHash
{
void insert(const TKey& key, const TValue& val) {this->val = val;}
const TValue& value(const TKey& key) const { return val; }
TValue val;
};

template <typename... Args> struct MultiKeyHash;

template <typename TKey, typename... Args>
struct MultiKeyHash<TKey, Args...> : QHash<TKey, MultiKeyHash<Args...>>
{
typedef TKey KeyType;
typedef typename MultiKeyHash<Args...>::ValueType ValueType;
typedef QHash<KeyType, MultiKeyHash<Args...>> QHashType;

using QHashType::insert;
using QHashType::value;

MultiKeyHash() {}

MultiKeyHash(const TKey &key, const Args&... args)
{
this->insert(key, MultiKeyHash<Args...>(args...));
}

void insert(const TKey &key, const Args&... args)
{
MultiKeyHash<Args...> val(args...);
this->insert(key, val);
}
template <typename TKey1, typename ... Args1>
const ValueType& value(const TKey1 &key1, const Args1&... args1) const
{
MultiKeyHash<Args...> const& val = this->value(key1);
return val.value(args1...);
}
};

template <typename TKey, typename TValue>
struct MultiKeyHash<TKey, TValue> : QHash<TKey, TValue>
{
typedef TKey KeyType;
typedef TValue ValueType;
typedef QHash<KeyType, ValueType> QHashType;

MultiKeyHash() {}

MultiKeyHash(const TKey &key, const TValue& val)
{
this->insert(key, val);
}
};

void test1()
{
MultiKeyHash<int, double> hash;
hash.insert(10, 200.5);
double v = hash.value(10);
std::cout << "Value: " << v << std::endl;
}

void test3()
{
MultiKeyHash<int, int, int, double> hash;
hash.insert(10, 10, 10, 20.5);
double v = hash.value(10, 10, 10);
std::cout << "Value: " << v << std::endl;
}

int main()
{
test1();
test3();
return 0;
};

运行程序的输出:

Value: 200.5Value: 20.5

关于c++ - 从参数包中删除最后一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com