c++ - 编译时绑定(bind) C++ 模板?

标签 c++ templates corba

我试图弄清楚如何让 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 以获得 CC 始终是 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/

相关文章:

c++ - 在 C/C++ 中提取一个 tar.xz

c++ - 翻译时,这些方括号会做什么?

symfony - 如何在 Symfony 中组织模板

c++ - 为模板参数使用类型定义的默认类型

c++ - CORBA::ORB_init 泄漏内存

c++ - 我不明白为什么这个模板特化在 VS 2010 中失败

c++ - 为什么不能 "combine with previous declaration specifier"

Magento 小部件不显示自定义模板

java - Java CORBA 中的 POA 损坏问题

c++ - resolve_initial_references 导致 SystemException