c++ - 模板参数的默认参数?

标签 c++ templates c++17

#include <cstdint>

class MyBar {};
class DifferentBar {};

class Foo{
public:
    template <class Bar = MyBar>
    Foo(uint32_t i) {}
};

int main() {
    auto pFoo1 = new Foo(3);
    auto pFoo2 = new Foo<DifferentBar>(3);
}

我试图理解为什么编译器给我一个错误:

template_ctor.cpp: In function ‘int main()’:
template_ctor.cpp:14:19: error: ‘Foo’ is not a template
  auto pFoo2 = new Foo<DifferentBar>(3);
                   ^~~

是因为模板参数的默认参数只在类级别有效吗?当我改为:

template <class Bar = MyBar>
class Foo{
public:
    Foo(uint32_t i) {}
};

它编译。<​​/p>

提前致谢。

最佳答案

当你写作时

class Foo{
public:
    template <class Bar = MyBar>
    Foo(uint32_t i) {}
};

你说Foo是具有模板构造函数的非模板类。

当你写作时

auto pFoo2 = new Foo<DifferentBar>(3);

你给Foo模板参数;但是Foo是一个非模板类。

所以错误。

改变 Foo在具有默认参数模板的模板类中

<class Bar = MyBar>
class Foo{
public:
    Foo(uint32_t i) {}
};

你现在有了new Foo<DifferentBar>(3);是正确的,也可以编译 new Foo(3);因为使用了默认模板参数 ( MyBar )。

关于c++ - 模板参数的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388925/

相关文章:

javascript - 如何为此目标更改 css 文件?

c++ - 在 C++17 中跟踪相对内存使用情况

c++ - 基于范围的 std::move 意外调用复制构造函数

c++ - 除了与旧标准代码一起使用外,Boost 库在包含在 C++ 中后会发生什么变化?

c++ - "using"为 "<template <class> class T>"

php - 使用 PHP 将 C++ 编译为二进制文件

c++ - 将 array<String^>^ 转换为 std::vector<std::string>

c++ - 将字符串写入长度超过 4095 个字符的文件

c++ - 函数范围内的静态 constexpr - MSVC 的行为是编译器错误吗?

c++ - 实例化和未实例化模板的部分模板特化