这是“显式”关键字。
template <typename T>
struct foo
{
explicit foo(T const *)
{
}
};
template <typename T>
struct bar
{
bar(T const *)
{
}
};
int main(int argc, char **argv)
{
int a;
foo<int> f = &a; // doesn't work
bar<int> b = &a; // works
}
“explicit”关键字防止构造函数用于隐式类型转换。考虑以下两个函数原型:
void baz(foo<int> const &);
void quux(bar<int> const &);
使用这些定义,尝试使用 int 指针调用这两个函数:
baz(&a); // fails
quux(&a); // succeeds
在 quux 的情况下,您的 int 指针被隐式转换为条形。
编辑:要扩展其他人的评论,请考虑以下(相当愚蠢的)代码:
void bar(std::auto_ptr<int>);
int main(int argc, char **argv)
{
bar(new int()); // probably what you want.
int a;
bar(&a); // ouch. auto_ptr would try to delete a at the end of the
// parameter's scope
int * b = new int();
bar(b);
*b = 42; // more subtle version of the above.
}