我想有一个类Boxed_value
可以InBox
其他类型(从开始int
,double
,string
...),类似于object
在C#
。该类类型可以进一步传递给Unbox
它所使用的函数。这些功能将获得参考:
void receiver( Boxed_value & bv ) {}
因此,它不应该是模板。要么?我需要一个配方...该UnBox
功能可以单独设置并进行模板化。在这种情况下receiver
可以获得2个参数:
void receiver( Boxed_value & bv, Engine & eng ) {}
下面的实现是虚拟的,尚未编译。
struct Boxed_value {
void inbox(int v) { _iv = v; }
void inbox(double v) { _dv = v; }
void inbox(std::string & v) { _sv = v; }
int _iv;
double _dv;
std::string _sv;
};
struct Engine {
template<typename T>
T unbox(Boxed_value bv) {
if (std::is_same<T, typeid(bv._iv).name()>::value) { return _iv };
if (std::is_same<T, typeid(bv._dv).name()>::value) { return _dv };
if (std::is_same<T, typeid(bv._sv).name()>::value) { return _sv };
}
};
注意,在编译时,每个if
子句都必须实例化。这意味着您将在function中返回不同的类型unbox
。
您应该比较成员的类型std::is_same
,但不能比较typeid(bv._iv).name()
,它不是type而是具有type的对象const char*
。
您可以应用Constexpr If(自C ++ 17起)。
如果值为
true
,则丢弃statement-false(如果存在),否则,丢弃statement-true。
并使用decltype
(自C ++ 11起)获取成员的类型。
例如
template<typename T>
T unbox(const Boxed_value& bv) {
if constexpr (std::is_same<T, decltype(bv._iv)>::value) { return bv._iv };
else if constexpr (std::is_same<T, decltype(bv._dv)>::value) { return bv._dv };
else if constexpr (std::is_same<T, decltype(bv._sv)>::value) { return bv._sv };
}
在C ++ 17之前,您可以应用完全专业化。
template<typename T>
T unbox(const Boxed_value& bv);
template<>
decltype(Boxed_value::_iv) unbox<decltype(Boxed_value::_iv)> (const Boxed_value& bv) { return bv._iv; }
template<>
decltype(Boxed_value::_dv) unbox<decltype(Boxed_value::_dv)> (const Boxed_value& bv) { return bv._dv; }
template<>
decltype(Boxed_value::_sv) unbox<decltype(Boxed_value::_sv)> (const Boxed_value& bv) { return bv._sv; }
PS:我将参数类型从更改Boxed_value
为const Boxed_value&
,以避免不必要的复制。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句