【发布时间】:2013-04-26 17:55:49
【问题描述】:
g++ 在该示例上遇到错误。
我有一个类Option,其中包含一个std::string
OptionValue 继承自 Option,具有模板类型和 std::string 类型的模板化参数作为键。
OptionManager 在std::map<std::string, Option*> 中管理OptionValue
OptionManager 有一个成员函数create :
template <typename T, std::string & key>
void create(const T & value);
g++ 如果我不调用,请不要抱怨:
OptionManager *manager = new OptionManager;
manager->create<int, "my_key">(3);
g++ 不喜欢create 调用,这是错误:
no matching function for call to OptionManager::create(int)
如果有人能帮我指路,我非常感谢他!!! :)
代码如下:
Option.hpp
class Option
{
public:
Option(std::string & key) :
key_(key)
{}
virtual ~Option()
{}
protected:
std::string key_;
};
OptionValue.hpp
template <typename T, std::string & key>
class OptionValue : public Option
{
public:
OptionValue<T, key>(T val) :
Option(key),
val_(val)
{}
virtual ~OptionValue()
{}
private:
T val_;
};
OptionManager.hpp
class OptionManager
{
public:
OptionManager(){}
~OptionManager(){}
template <typename T, std::string & key>
void create(const T & value)
{
Option *tmp;
tmp = new OptionValue<T, key>(value);
this->list_.insert(t_pair(key, tmp));
}
private:
std::map<std::string, Option*> list_;
typedef std::map<std::string, Option*>::iterator t_iter;
typedef std::pair<std::string, Option*> t_pair;
};
main.cpp
int main()
{
OptionManager *manager;
manager = new OptionManager;
manager->create<int, "my_key">(3);
return 0;
}
g++ 错误
main.cpp: In function ‘int main()’:
main.cpp:8:35: error: no matching function for call to ‘OptionManager::create(int)’
main.cpp:8:35: note: candidate is:
OptionManager.hpp:14:12: note: template<class T, std::string& key> void OptionManager::create(const T&)
【问题讨论】:
-
这是我多年来见过的最原始的代码格式。太可怕了。
标签: c++ templates template-matching