【问题标题】:Compile time binding a C++ template?编译时绑定 C++ 模板?
【发布时间】:2012-11-17 02:27:41
【问题描述】:

我试图弄清楚如何让 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),但我不明白语法。这一切都可以在宏中完成,但如果可以的话,我宁愿把它作为“真正的”模板。

有什么建议吗?

【问题讨论】:

  • 我猜有一个&lt;&lt;= 操作符知道如何处理一个左侧,它是一个CORBA::Any 的引用和一个在集合中的右侧[@ 987654333@, CORBA::Long, CORBA::Double... 等等] 那么你引入这个c_to_corba 函数而不是增强&lt;&lt;= 目标CORBA::Any 来接受简单类型有充分的理由吗?
  • 这是corba_to_c 的对,这会稍微复杂一些。我向我试图帮助解决此问题的人问了同样的问题,他对此有一些问题。

标签: c++ templates corba


【解决方案1】:

这样更好吗?

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 总是需要一个类型,但如果您遇到错误,这可能是解决方法。

【讨论】:

  • 看起来不错。您介意解释一下顶部的空struct 等吗?
  • @AaronD.Marasco:它不是一个空结构,它只是一个结构模板的声明(根本没有定义,空或其他)。声明是必要的,因为接下来的三行是特化的,但您不能特化尚未声明的模板。
猜你喜欢
  • 2015-07-27
  • 2022-01-11
  • 2016-07-23
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多