如果我被允许做以下事情:
template <typename T = int>
class Foo{
};
为什么不允许我做以下主要?
Foo me;
但我必须说明以下几点:
Foo<int> me;
c++ 11引入了默认模板参数,现在我完全理解不了它们。
如果我被允许做以下事情:
template <typename T = int>
class Foo{
};
为什么不允许我做以下主要?
Foo me;
但我必须说明以下几点:
Foo<int> me;
c++ 11引入了默认模板参数,现在我完全理解不了它们。
当前回答
在c++ 17中,你确实可以做到。
这个特性被称为类模板参数推断,它为声明模板类型变量的方式增加了更多的灵活性。
So,
template <typename T = int>
class Foo{};
int main() {
Foo f;
}
现在是合法的c++代码。
其他回答
在c++ 17中,你确实可以做到。
这个特性被称为类模板参数推断,它为声明模板类型变量的方式增加了更多的灵活性。
So,
template <typename T = int>
class Foo{};
int main() {
Foo f;
}
现在是合法的c++代码。
你不允许那样做,但你可以这样做
typedef Foo<> Fooo;
然后做
Fooo me;
有些不同的情况,而且比较晚,但涉及到一个模板函数。GCC 11.2似乎不能编译这个:
template <typename T = int>
struct Test {};
template<typename T> void foo(T& bar) {}
int main()
{
Test t;
foo<Test>(t);
}
但是没有问题
template <typename T = int>
struct Test {};
template<typename T> void foo(T& bar) {}
int main()
{
Test t;
foo<Test<>>(t);
}
当然
template <typename T = int>
struct Test {};
template<typename T> void foo(T& bar) {}
int main()
{
Test t;
foo(t);
}
有效-但有时需要显式强制该类型。这是编译器错误吗?
你可以使用以下方法:
Foo<> me;
让int作为模板参数。尖括号是必要的,不能省略。
注意:
Foo我;从c++ 17开始,没有模板参数是合法的。请看这个答案:https://stackoverflow.com/a/50970942/539997。
适用于c++ 17之前的原始答案:
你必须做到:
Foo<> me;
模板参数必须存在,但可以将其保留为空。
可以把它想象成一个只有一个默认参数的函数foo。表达式foo不会调用它,但foo()会。参数语法必须仍然存在。这是一致的。