且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们必须指定<>具有默认参数的模板类?

更新时间:2023-11-30 22:11:58


为什么是这种行为的原因?

Why is the reason of this behaviour ?

这是因为函数可以重载,而类型不能。

It's because functions can be overloaded, and types can't.

在编写函数调用时,编译器将填充所有函数的重载集合它可以找到具有该名称的名称,然后找出与传递的参数匹配的名称。现在,为了使它与函数模板完全兼容,它允许从参数中推导出模板参数类型。因为通常允许使用类型参数推论,所以即使默认使用参数,它也适用于您的情况。

When you write a function call, the compiler populates an overload set of all the functions it can find with that name, and then figures out which ones match the argument(s) passed. Now, for this to work cleanly with function templates, it allows the template argument types to be deduced from the parameters. Because type parameter inference is allowed in general, it works for your case even when the parameter is defaulted instead.

但是,类型不会过载。虽然 myFunction< true>() myFunction< false>()都与他们参与的程度有关在相同的重载集中, myClass< true> myClass< false> 是独立的且与不相关类型。在不重载类型名称的情况下,没有动机为隐式命名完全专业化的模板类添加特殊情况。这些参数永远不能被推断出来,因此只有在所有参数都默认设置的情况下,它才具有特殊的语法。

Types, however, aren't overloaded. While myFunction<true>() and myFunction<false>() are both related to the extent they'll participate in the same overload set, myClass<true> and myClass<false> are separate and unrelated types. With no equivalent of overloading on type names, there's no motivation to add a special case for implicitly naming a fully-specialized template class. The parameters can never be inferred, so it would amount to special syntax only for the case where they're all defaulted.


避免这种情况的技巧?

Is there any trick to avoid that ?

通常,如果要获得模板类的模板参数推导,可以提供模板函数包装器(这最适合C ++ 11 auto)

In general, if you want to get template argument deduction for template classes, you can provide a template function wrapper (this works best with C++11 auto)

template <bool Option=false> class MyClass {};
template <bool Option=false> MyClass<Option> make_my_class() {
    return MyClass<Option>();
}
// ...
auto z = make_my_class();

否则,我认为使用 typedef (as根据雷米的评论)是***的选择。

Otherwise, I think using typedef (as per Remy's comment) is the best option.