作为具有 THAT 函数作为模板参数的 class 字段的模板参数
Function as template argument for a field of a class that has THAT function as template argument
用代码更容易解释。
例子
我有一个哈希映射数据结构,其模板如下:-
template<class K,class T,long (* K_hashingFunction)(K&)> class AMap{
// ^ Key ^Value ^ Hashing function for Key
}
如我所愿。
然后我想声明一个迭代器class如下:-
template<class K,class T,long (* K_hashingFunction)(K&)> class AMap_iterator{
AMap<K,T, ????? >* mapPtr=nullptr; //How should I declare its type?
}
问题:将mapPtr声明为字段的正确方法是什么?
AMap<K,T, K_hashingFunction >* mapPtr=nullptr; //?
AMap<K,T, &K_hashingFunction >* mapPtr=nullptr; //?
AMap<K,T, *K_hashingFunction> * mapPtr=nullptr; //?
所有这些都给我一个智能感知错误:"Cannot substitute template argument"
这是正确的:
AMap<K,T, K_hashingFunction >* mapPtr=nullptr;
我们只是复制所有模板参数 - 无需修改。请注意,取消引用函数指针也应该有效,因为该函数只会衰减回指向的指针。
由于注入了 class 个名字,我们可以简化为:
AMap* mapPtr = nullptr;
只是添加到 Barry 的回答中。
AMap<K,T, &K_hashingFunction >* mapPtr=nullptr;
是不正确的,因为表达式 &K_hashingFunction
会 return 指向函数 的指针。不是 函数指针。
用代码更容易解释。
例子
我有一个哈希映射数据结构,其模板如下:-
template<class K,class T,long (* K_hashingFunction)(K&)> class AMap{
// ^ Key ^Value ^ Hashing function for Key
}
如我所愿。
然后我想声明一个迭代器class如下:-
template<class K,class T,long (* K_hashingFunction)(K&)> class AMap_iterator{
AMap<K,T, ????? >* mapPtr=nullptr; //How should I declare its type?
}
问题:将mapPtr声明为字段的正确方法是什么?
AMap<K,T, K_hashingFunction >* mapPtr=nullptr; //?
AMap<K,T, &K_hashingFunction >* mapPtr=nullptr; //?
AMap<K,T, *K_hashingFunction> * mapPtr=nullptr; //?
所有这些都给我一个智能感知错误:"Cannot substitute template argument"
这是正确的:
AMap<K,T, K_hashingFunction >* mapPtr=nullptr;
我们只是复制所有模板参数 - 无需修改。请注意,取消引用函数指针也应该有效,因为该函数只会衰减回指向的指针。
由于注入了 class 个名字,我们可以简化为:
AMap* mapPtr = nullptr;
只是添加到 Barry 的回答中。
AMap<K,T, &K_hashingFunction >* mapPtr=nullptr;
是不正确的,因为表达式 &K_hashingFunction
会 return 指向函数 的指针。不是 函数指针。