bad*_*ash 8 c++ templates default-parameters template-argument-deduction
我有这个代码:
struct A{};
template<class T = A>
struct B {
void foo() {}
};
B b; //Error: missing template arguments before 'b'
//Error: expected ';' before 'b'
//More errors
b.foo()
Run Code Online (Sandbox Code Playgroud)
如果我foo()使用相同的模板'signature'作为模板函数,编译器不会抱怨没有指定模板参数:
struct A {};
struct B {
template<class T = A>
void foo() {}
};
B b; //OK
b.foo()
Run Code Online (Sandbox Code Playgroud)
那么为什么我需要为带有默认参数的模板类指定参数,而不是为模板函数指定?我遗失了一些微妙之处吗?
原因是因为模板参数推断失败肯定.但我想知道原因.
正确的语法是这个(演示):
B<> b;
Run Code Online (Sandbox Code Playgroud)
A假定类模板的默认参数B.该<>部分告诉编译器这B是一个类模板,并要求它将默认参数作为模板参数.