C++/CLI中的未解析令牌
问题描述:
我正在为我创建的某个类获取链接器错误。C++/CLI中的未解析令牌
1>Dict.obj : error LNK2020: unresolved token (06000006) TwoKeyDict<System::String ^,int>::.ctor
1>Dict.obj : error LNK2020: unresolved token (06000007) TwoKeyDict<System::String ^,int>::Get
1>Dict.obj : error LNK2020: unresolved token (06000008) TwoKeyDict<System::String ^,int>::Put
1>Dict.obj : error LNK2020: unresolved token (06000009) TwoKeyDict<int,int>::.ctor
1>Dict.obj : error LNK2020: unresolved token (0600000A) TwoKeyDict<int,int>::Get
1>Dict.obj : error LNK2020: unresolved token (0600000B) TwoKeyDict<int,int>::Put
这些都是在我尝试使用类的所有地方。下面是类代码:
TwoKeyDict.h
#pragma once
using namespace System::Collections::Generic;
template<class K, class V>
public ref class TwoKeyDict
{
private:
Dictionary<K, Dictionary<K, V>^>^ underlyingDict;
public:
TwoKeyDict();
V Get(K key1, K key2);
void Put(K key1, K key2, V value);
};
TwoKeyDict.cpp
#include "StdAfx.h"
#include "TwoKeyDict.h"
template<class K, class V>
TwoKeyDict<K, V>::TwoKeyDict() {
underlyingDict = gcnew Dictionary<K, Dictionary<K, V>^>();
}
template<class K, class V>
V TwoKeyDict<K, V>::Get(K key1, K key2) {
if (underlyingDict->ContainsKey(key1)) {
if (underlyingDict[key1]->ContainsKey(key2)) {
return underlyingDict[key1][key2];
}
}
return nullptr;
}
template<class K, class V>
void TwoKeyDict<K, V>::Put(K key1, K key2, V value) {
if (underlyingDict->ContainsKey(key1)) {
Dictionary<K, V>^>^ secondLayerDict = underlyingDict[key1];
if (secondLayerDict->ContainsKey(key2)) {
secondLayerDict[key2] = value;
} else {
secondLayerDict->Add(key2, value);
}
} else {
Dictionary<K, V>^>^ secondLayerDict = gcnew Dictionary<K, V>^>();
secondLayerDict->Add(key2, value);
underlyingDict->Add(key1, secondLayerDict);
}
}
在地方,我试图用它我只是在做的#include“ TwoKeyDict.h“
答
模板进入头文件,所有用户都可以看到实现。
您确定要使用模板而不是通用?看起来你并没有从专业化中获益。
+0
我不认为我需要一个模板毕竟。当我决定使用哪一个时,我正在阅读的内容似乎暗示泛型不适用于原语,但似乎并非如此。那是对的吗? –
+0
@Alex:您正在考虑Java,其中原始元素被装箱;在.NET中,泛型与基元一样可以100%地工作。 – ildjarn
使用* generic *关键字来获取不需要.h文件的模板类泛型类。 C++版本(* template *关键字)没有外部链接,.NET版本(* generic *关键字)没有。 –
@HansPassant:泛型只是表面上类似于模板。他们比他们更像不同,国际海事组织。 –