gpt4 book ai didi

c++ - 特殊模板函数的作用

转载 作者:行者123 更新时间:2023-11-28 01:40:14 24 4
gpt4 key购买 nike

我有一个结构模板,例如:

template<typename KEY_T, typename VAL_T> 
struct pair
{
KEY_T key; VAL_T val;
};

VAL_T val可能不同(字符串、列表或其他)我想要的是重载 operator[]对于指定的模板结构 pair<std::string, std::list> ,而且只为它。怎么可能?

附言我正在编写一个 Ini-parser,我想访问像 settings[Section][Key] 这样的设置, 其中settings[Section]返回 pair<std::string, std::list<Entry>>settings[Section][Key]然后从 std::list<Entry> 返回字符串

最佳答案

类模板可以是特化的,或者是部分特化的:

template<typename T> 
struct pair<std::string, std::list<T>>
{
std::string key;
std::list<T> val;
T& operator[](...) {
//implement
}
};

或完全:

template<> 
struct pair<std::string, std::list<Entry>>
{
std::string key;
std::list<Entry> val;
Entry& operator[](...) {
//implement
}
};

作为旁注,请考虑将您的类放在指定的命名空间中。如果您还需要使用 std::pair,则更易于管理。

关于c++ - 特殊模板函数的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479514/

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