C++ 模板默认参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15373823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:19:21  来源:igfitidea点击:

Template default arguments

c++templates

提问by user633658

If I am allowed to do the following:

如果允许我执行以下操作:

template <typename T = int>
class Foo{
};

Why am I not allowed to do the following in main?

为什么我不允许在 main 中执行以下操作?

Foo me;

But I must specify the following:

但我必须指定以下内容:

Foo<int> me;

C++11 introduced default template arguments and right now they are being elusive to my complete understanding.

C++11 引入了默认模板参数,现在我完全理解它们是难以捉摸的。

回答by Joseph Mansfield

You have to do:

你必须要做:

Foo<> me;

The template arguments must be present but you can leave them empty.

模板参数必须存在,但您可以将它们留空。

Think of it like a function foowith a single default argument. The expression foowon't call it, but foo()will. The argument syntax must still be there. This is consistent with that.

把它想象成一个foo带有单个默认参数的函数。表达式foo不会调用它,但foo()会调用它。参数语法必须仍然存在。这与那是一致的。

回答by Paolo M

With C++17, you can indeed.

使用 C++17,您确实可以。

This feature is called class template argument deductionand add more flexibility to the way you can declare variables of templated types.

此功能称为类模板参数推导,可为声明模板化类型的变量的方式增加更多灵活性。

So,

所以,

template <typename T = int>
class Foo{};

int main() {
    Foo f;
}

is now legal C++ code.

现在是合法的 C++ 代码

回答by Andy Prowl

You can use the following:

您可以使用以下内容:

Foo<> me;

And have intbe your template argument. The angular brackets are necessary and cannot be omitted.

int成为您的模板参数。尖括号是必需的,不能省略。

回答by g24l

You are not allowed to do that but you can do this

你不被允许这样做,但你可以这样做

typedef Foo<> Fooo;

and then do

然后做

Fooo me;