【发布时间】:2014-04-21 22:35:41
【问题描述】:
观察下面的程序,其中一个函数既接受预期的类型,也接受属于该类型的 typedef 的任何类型。
//a user defined type
class Widget{};
//a function that takes a Widget
void function (Widget w){}
int main(){
//make a typedef (this is C++11 syntax for a typedef. It's the same thing)
using Gadget = Widget;
//make the two "different types" (well.. they're not really different as you will see)
Widget w;
Gadget g;
//call a function that should ONLY accept Widgets
function(w); //works (good)
function(g); //<- works (I do not want this to compile though)
}
如您所见,typedef 实际上并不区分新类型。我想改为从类型继承:
//inherit instead
class Gadget: public Widget{};
//make the two "different types"
Widget w;
Gadget g;
//call the function that should ONLY accept widgets
function(w); //works (good)
function(g); //<- works (I do not want this to compile though)
同样的问题。
看着boost,我想尝试一个强大的typedef:
#include <boost/serialization/strong_typedef.hpp>
//a user defined type
class Widget{};
//a function that takes the user defined type
void function (Widget w){}
int main(){
//try to strongly typedef
BOOST_STRONG_TYPEDEF(Widget, Gadget)
//make the two "different types"
Widget w;
Gadget g;
//call the function that should ONLY accept widgets
function(w);
function(g);
}
编译错误:
In member function ‘bool main()::Gadget::operator==(const main()::Gadget&) const’:
error: no match for ‘operator==’ (operand types are ‘const Widget’ and ‘const Widget’)
BOOST_STRONG_TYPEDEF(Widget, Gadget)
^
In member function ‘bool main()::Gadget::operator<(const main()::Gadget&) const’:
error: no match for ‘operator<’ (operand types are ‘const Widget’ and ‘const Widget’)
BOOST_STRONG_TYPEDEF(Widget, Gadget)
^
显然 BOOST_STRONG_TYPEDEF 仅适用于原始类型。
我尝试再次进行继承,但停止隐式转换:
//I want the functionality, but these are NOT the same type!
class Gadget: public Widget{
operator Widget() = delete;
};
那也没用。
问题:
- 为什么 boost strong_typedef 只对原始类型起作用?
- 如何“typedef”非原始类型以获得类似于 boost strong_typef 的功能?
【问题讨论】:
-
我想我会
class WidgetBase,然后class Widget: public WidgetBase;class Gadget: public WidgetBase. -
@zneak:
BOOST_STRONG_TYPEDEF就是这样做的。 -
@Deduplicator 查看实现 strong_typedef 使用成员而不是继承。
-
strong_typedef 并不是只适用于原始类型,而是要求参数类型是完全有序的(
operator==,operator<)你可以提供它们或者只使用 strong_typedef 中的代码减去排序。 -
你想要一个类型
Gadget,它类似于Widget,但不像Widget。退后一步想想你真正想要声明的内容是否会有所帮助?
标签: c++ c++11 boost types typedef