テンプレート化されたクラスをコンパイルしようとすると、リンカー エラーが発生します。私は C++ のテンプレート化されたプログラミングとコンパイラ (MSBuild/VS2012) の動作にあまり熱心ではなく、何が間違っていたのかを判断するのに苦労しています。/CLR でコンパイルしていますが、ソース ファイルをコンパイルしようとすると、次のような一連のリンカー エラー (LNK2005) が発生します。
ISaveStrategy.h:
#pragma once
#pragma unmanaged
template<class T>
class ISaveStrategy
{
public:
enum SaveResult {OK, Error};
virtual SaveResult Save(const T& itemToSave) = 0;
};
SaveToXmlStrategy.h:
#pragma once
#include <gcroot.h>
#include "ISaveStrategy.h"
#pragma unmanaged
namespace System{namespace Xml{ref class XmlWriter;}}
template<class T>
class SaveToXmlStrategy : public ISaveStrategy<T>
{
public:
SaveToXmlStrategy(gcroot<System::Xml::XmlWriter^> writer)
: m_writer(writer)
{}
virtual SaveResult Save(const T& itemToSave);
private:
gcroot<System::Xml::XmlWriter^> m_writer;
};
SaveToXmlStrategy.cpp:
#pragma once
#include "stdafx.h"
#include "SaveToXmlStrategy.h"
#include "IKeyFrame.h"
#include "IKeyFrameTransition.h"
#include "ICueProvider.h"
#pragma managed
using namespace System;
using namespace System::Text;
template class SaveToXmlStrategy<IKeyFrameTransition>;
SaveToXmlStrategy<IKeyFrameTransition>::SaveResult SaveToXmlStrategy<IKeyFrameTransition>::Save(const IKeyFrameTransition& keyFrame)
{
return SaveResult::OK;
}
template class SaveToXmlStrategy<ICueProvider>;
SaveToXmlStrategy<ICueProvider>::SaveResult SaveToXmlStrategy<ICueProvider>::Save(const ICueProvider& keyFrame)
{
return SaveResult::OK;
}
template class SaveToXmlStrategy<IKeyFrame>;
SaveToXmlStrategy<IKeyFrame>::SaveResult SaveToXmlStrategy<IKeyFrame>::Save(const IKeyFrame& keyFrame)
{
SaveResult result = SaveResult::OK;
return result;
}
実装.cpp:
#pragma once
#include "SaveToXmlStrategy.cpp"
//inside a function body :
ISaveStrategy<IKeyFrame>& keyFrameSaver = SaveToXmlStrategy<IKeyFrame>(xmlWriter.get());