我试图弄清楚如何让 C++ 模板使用查找表来执行其功能,但在编译时而不是运行时。我很难用语言表达,所以这里有一个例子,以及我目前拥有的丑陋的模板 + 预处理器宏组合:
template<class T_POD, class T_Corba>
inline void c_to_corba_base(T_POD &In, CORBA::Any &Out) {
Out <<= static_cast<T_Corba>(In);
}
#define C_TO_CORBA_PAIR(T_POD, T_CORBA) \
inline void c_to_corba(T_POD &In, CORBA::Any &Out) { \
c_to_corba_base<T_POD, T_CORBA>(In, Out); \
}
C_TO_CORBA_PAIR(short, CORBA::Short)
C_TO_CORBA_PAIR(long, CORBA::Long)
C_TO_CORBA_PAIR(double, CORBA::Double)
// etc.
所以你可以看到,它将 A
类型转换为 B
以获得 C
。 C
始终是 CORBA::Any
。但是 B
依赖于 A
(在编译时已知)。
我做了一些研究,它看起来像 Boost::MPL::bind
可以做我需要的(我们已经需要 Boost)但我不明白语法。它本可以全部在宏中完成,但如果可以的话,我宁愿将其作为“真正的”模板。
有什么建议吗?
最佳答案
这样更好吗?
template<typename> struct CorbaTypeMap;
template<> struct CorbaTypeMap<short> { typedef CORBA::Short type; };
template<> struct CorbaTypeMap<long> { typedef CORBA::Long type; };
template<> struct CorbaTypeMap<double> { typedef CORBA::Double type; };
template<typename T_POD>
inline void c_to_corba(T_POD &In, CORBA::Any &Out) {
Out <<= static_cast< /* typename */ CorbaTypeMap<T_POD>::type >(In);
}
我认为您不需要那个 typename
关键字,因为 static_cast
总是需要一个类型,但是如果您遇到错误,这可能是解决方法.
关于c++ - 编译时绑定(bind) C++ 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13427086/