在base.h中:
template <typename T, typename T2> class Base
{
public:
virtual int Foo(T param1) = 0;
virtual int Bar(T param1, T2 param2) = 0;
};
在derived1.h中:
template <typename T, typename T2> class Derived1 : public Base<T, T2>
{
public:
virtual int Foo(T param1);
virtual int Bar(T param1, T2 param2);
};
在derived2.h中:
template <typename T, typename T2> class Derived2 : public Base<T, T2>
{
public:
virtual int Foo(T param1);
virtual int Bar(T param1, T2 param2);
};
在myfile.cpp中:
extern "C" template<typename T, typename T2> Base<T, T2> *my_func(template<typename T, typename T2> Base<T, T2> *param)
{
if( <cond1> )
param<char, char> = new Derived1<char, char>();
if( <cond2> )
param<SQLWCHAR, SQLWCHAR> = new Derived2<SQLWCHAR, SQLWCHAR>();
return param<T, T1>;
}
此代码是否将在MSVC 2010和gcc中编译?
我已经在切换编译器方面遇到了麻烦,所以想在到达之前先问一下......
另外:我不希望功能被模板化。我希望传递模板对象并从函数返回。
谢谢。
[编辑]
我刚刚回家试了一下:
extern "C" __declspec(dllexport) template<typename T, typename T2> Base<T, T2> *my_func(Base<T, T2> *param)
得到了这个:
warning C4091: '__declspec(dllexport)' : ignored on left of 'int' when no variable is declared
error C2143: syntax error : missing ';' before ''template<''
如何让它发挥作用?该功能需要导出,因此它应该具有&#34; C&#34;键。
另一种方法是将函数定义为C ++并从dll / so中获取其符号名称,这很痛苦。
[/编辑]
[EDIT2}
我实际想到的是写下这样的东西:
class CMainFrame
{
private:
template<typename T, typename T2> Base<T, T2> *m_pBase;
public:
CMainFrame();
~CMainFrame();
int CallFunc();
};
CMainFrame::CMainFrame() {}
CMainFrame::~CMainFrame()
{
delete m_pBase;
}
int CMainFrame::CallFunc()
{
template<typename T, typename T2> Base<T, T2> *base = NULL;
m_pBase<T, T2> = my_func( base );
}
[/ EDIT2]
答案 0 :(得分:0)
template<typename T, typename T2>
Base<T, T2> *my_func(Base<T, T2> *param)
{
param = new Derived<T, T2>();
return param;
}
或
Base<char, char> *my_func(Base<char, char> *param)
{
param = new Derived<char, char>();
return param;
}
请注意,param
一个参数似乎没有任何理由,如果它仅被用作局部变量,那么这会更好:
template<typename T, typename T2>
Base<T, T2> *my_func()
{
Base<T, T2> *param = new Derived<T, T2>();
return param;
}
或
Base<char, char> *my_func()
{
Base<char, char>* param = new Derived<char, char>();
return param;
}
基于OP的澄清:试试这个。如果你确实需要传递param
,你可以将其声明为Base<T,T2>* param
- 但我认为你不需要。我也不确定为什么param
需要Base<T,T2>
类型,因为在编译之后, 属于某种实际类型Base<char,char>
或Base<SQWLCHAR,SQWLCHAR>
或者你有什么。但无论如何,这就是。
template<typename T, typename T2>
Base<T, T2> *my_func()
{
Base<T, T2>* param;
if( <cond1> )
param = new Derived1<char, char>();
else if( <cond2> )
param = new Derived2<SQLWCHAR, SQLWCHAR>();
else
param = ??whatever it should be if neither condition applies??;
return param;
}
好的,根据 next 澄清,这看起来像是在尝试:
class Database //an interface: no data, function prototypes only
{
public:
virtual QueryResultType query (const char* queryText) = 0;
...
};
class SQLiteDatabase: public Database
{
public:
QueryResultType query (const char* queryText);
//this function has a body, and deals with queries the SQLite way
};
...
Database* myDatabase = new SQLiteDatabase ();