省略C++模板中的空<>

Ommit empty <> in C++ templates

本文关键字:gt lt C++ 省略      更新时间:2023-10-16

是否有一种方法可以省略C 11中的空<>,以使语法更加好,这意味着为模板类编写Foo而不是Foo<>

我很明显我可以重命名/名称空间等。但是我想优化两个字符,不要将用户与新名称混淆或强迫他键入比以前更多。

完整示例:

template<int N = 1>
class Foo{};
using Foo = Foo<>;
int main()
{
  Foo foo; // I want to be able to write this.
  Foo<> foo; // Works but is ugly.
}

您只有一个使该语法工作的选项,并且可以切换到 C 17 。然后,您可以将模板参数删除,因为默认的模板参数始终可以作为新类模板参数扣除的一部分推导(有时称为"扣除指南")。

template<int N = 1>
class Foo{};
int main() {
    { Foo foo; }
    { Foo<> foo; }
}

活在Wandbox上


取决于您可以做出的权衡,有两种解决方案可与 c 11

一起使用
  1. 使用别名模板使用其他名称。

    template<int N = 1>
    class Foo{};
    using FooNoArgs = Foo<>;
    int main() {
        { FooNoArgs foo; }
        { Foo<> foo; }
    }
    

    活在wandbox上

  2. 如果需要访问模板变体,将模板移至其自己的名称空间与本地using结合。

    namespace foo {
    template<int N = 1>
    class Foo{};
    }
    using Foo = foo::Foo<>;
    int main() {
        { Foo foo; }
        { using foo::Foo; Foo<> foo; }
    }
    

    活在wandbox上