c++ - 默认模板参数 : Why does the compiler complain about not specifying template argument?

标签 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()

如果我将 foo() 作为具有相同模板“签名”的模板函数,编译器不会提示没有指定模板参数:

struct A {};

struct B {
    template<class T = A>
    void foo() {}
};

B b; //OK
b.foo()

那么为什么我需要为带有默认参数的模板类指定参数,而不是为模板函数指定参数呢?我是否遗漏了一些微妙之处?

原因肯定是因为模板参数推导失败。但我想知道为什么。

最佳答案

正确的语法是这样的(demo):

B<> b; 

默认参数 A假定为类模板 B . <>部分告诉编译器 B是一个类模板,并要求它采用默认参数作为它的模板参数。

关于c++ - 默认模板参数 : Why does the compiler complain about not specifying template argument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11231372/

相关文章:

c++ - 当我不使用 new 或 delete 时,为什么会出现堆损坏?

c++ - 没有 C++ 的 ROOT

C++ 模板错误:没有用于调用 std::vector<int, std::allocator<int>> 的匹配函数

c++ - 使用派生类实例作为默认参数值

c++ - ubuntu命令获取C++程序中的所有功能

c++ - 内存文件 : Adding an int offset?

c++ - 模板特化别名

c++ - 从模板分配空指针

python - 如何在 Python 的另一个函数中找出特定函数参数的默认值?