我试图指定一个模板类的功能,该功能只能在使用特定类型(KEY作为std::string
和VALUE作为std::string
)创建类的对象时使用。专门化模板成员函数
我的模板(Dictionary.h
),简化为:
#ifndef QB_DICTIONARY_H
#define QB_DICTIONARY_H
#include <map>
#include <string>
namespace QB {
template<typename KEY, typename VALUE, typename COMPARE = std::less<KEY>>
class Dictionary {
public:
typedef typename std::map<KEY, VALUE, COMPARE>::iterator iterator;
typedef typename std::map<KEY, VALUE, COMPARE>::const_iterator const_iterator;
Dictionary() {
}
Dictionary(const std::map<KEY, VALUE, COMPARE> & value) {
this->value = value;
}
typename iterator begin() {
return value.begin();
}
typename const_iterator begin() const {
return value.cbegin();
}
typename iterator end() {
return value.end();
}
typename const_iterator end() const {
return value.cend();
}
// Trying to have the function work only when the template KEY and VALUE are of type std::string
const std::string implode<std::string, std::string>(const std::string & valueSeparator, const std::string & pairSeparator) const {
std::string result;
for (iterator i = begin(); i != end(); i++) {
if (i != begin()) {
result += pairSeparator;
}
result += iterator->first;
result += valueSeparator;
result += iterator->second;
}
return result;
}
private:
std::map<KEY, VALUE, COMPARE> value;
};
}
#endif
的破灭功能是一个我试图实现。试图编译在这上面的结果:
1>d:\cloud storage\onedrive\projects\qb\qb\dictionary.h(115): error C2143: syntax error: missing ';' before '<'
1> d:\cloud storage\onedrive\projects\qb\qb\dictionary.h(133): note: see reference to class template instantiation 'QB::Dictionary<KEY,VALUE,COMPARE>' being compiled
1>d:\cloud storage\onedrive\projects\qb\qb\dictionary.h(115): error C2334: unexpected token(s) preceding '{'; skipping apparent function body
我不知道我应该如何实现这一点。任何提示?
编辑:
我遇到了一些新问题,同时尝试@ TartanLlama的答案。
我当前的代码如下(不相关的部分排除在外): Dictionary.h
:
#ifndef QB_DICTIONARY_H
#define QB_DICTIONARY_H
#include <map>
#include <string>
#include <type_traits>
namespace QB {
template<typename KEY, typename VALUE, typename COMPARE = std::less<KEY>>
class Dictionary {
public:
// ...
const std::string implode(const std::string &, const std::string &) const;
// ...
};
template<typename K=KEY, typename V=VALUE, typename COMPARE = std::less<KEY>>
std::enable_if_t<std::is_same<std::string, K>{} && std::is_same<std::string, V>{}, const std::string> Dictionary<K, V, COMPARE>::implode(const std::string & valueSeparator, const std::string & pairSeparator) const {
// ...
}
}
#endif
这可能会来派上用场。它工作,所以我upvoted它,但coincoin的答案是更加优雅。不管怎样,谢谢! – Qub1
@ Qub1要注意的一件事是,如果你做错了什么,这些解决方案会给你一个编译时错误,而coincoin的解决方案会给你一个链接时错误。 – TartanLlama
我注意到了。这可能会使调试变得困难。是否有可能将两种解决方案结合起来? – Qub1