我希望能够将继承自的对象的引用DBMetaData
作为另一个类的非类型模板参数传递DBVar
:
#include <iostream>
class DBMetaData
{
public:
virtual const char *description( ) const = 0;
};
class DBMetaData_NT
: public DBMetaData
{
public:
const char *description( ) const
{ return "Useless description."; }
};
#if DO_WHAT_I_WANT
template< const DBMetaData &Metadata >
#else
template< typename MetadataType,
const MetadataType &Metadata >
#endif // DO_WHAT_I_WANT
class DBVar
{
public:
/// Descrição da variavel.
const char *description( ) const
{ return Metadata.description( ); }
};
DBMetaData_NT _md_u1;
#if DO_WHAT_I_WANT
DBVar< _md_u1 > _u1;
#else
DBVar< DBMetaData_NT, _md_u1 > _u1;
#endif // DO_WHAT_I_WANT
int main( )
{
std::cout << "_md_u1.description( ) = " << _md_u1.description( ) << std::endl;
std::cout << "_u1.description( ) = " << _u1.description( ) << std::endl;
return 0;
}
我可以编译并运行上面的示例,但我需要明确指定继承的类型。
如果我尝试编译它定义DO_WHAT_I_WANT
(我想将类型的引用或指针传递给DBMetaData
任何继承类的对象),我会收到错误消息:
templ_inh_arg.cpp:36:15: error: could not convert template argument ‘_md_u1’ to ‘const DBMetaData&’
templ_inh_arg.cpp:36:20: error: invalid type in declaration before ‘;’ token
为什么我不能通过_u1
,那是DBMetaData_NT
继承自DBMetaData
as 参数的类型DBVar< _md_u1 > _u1;
?
有什么办法可以得到我想要的吗?
谢谢!
编辑:
正如@ecatmur 所建议的,用函数指针替换模板参数解决了我的问题,而且我必须注意,使我的代码更具可读性。
#include <iostream>
class DBMetaData
{
public:
/// Descrição da variavel.
virtual const char *description( ) const = 0;
};
class DBMetaData_NT
: public DBMetaData
{
public:
const char *description( ) const
{ return "Useless description."; }
};
typedef const DBMetaData &( *metadata )( );
template< metadata Metadata >
class DBVar
{
public:
/// Descrição da variavel.
const char *description( ) const
{ return Metadata( ).description( ); }
};
const DBMetaData & _md_u1_metadata( )
{
static const DBMetaData_NT _md_u1;
return _md_u1;
}
DBVar< _md_u1_metadata > _u1;
int main( )
{
std::cout << "_md_u1_metadata( ).description( ) = " << _md_u1_metadata( ).description( ) << std::endl;
std::cout << "_u1.description( ) = " << _u1.description( ) << std::endl;
return 0;
}