编译这个:
#include <iostream>
#include <memory>
template <auto val = 42>
struct A
{
A()
{
std::cerr << val << "\n";
}
};
int main(int argc, const char* argv[])
{
std::shared_ptr<A> a_ptr {new A {}};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出error: use of class template 'A' requires template arguments. 尽管我为非类型模板参数提供了默认值,并希望编译器能够以某种方式看到和使用它。我在这里想念什么?
谢谢。
它仍然是一个模板,并且仍然需要<and >:
std::shared_ptr<A<>> a_ptr {new A<> {}};
Run Code Online (Sandbox Code Playgroud)
想想这个。如果您有一个带有默认参数的函数:
int foo(int baz=42);
Run Code Online (Sandbox Code Playgroud)
你认为你可以简单地调用它而无需括号吗?
int bar=foo;
Run Code Online (Sandbox Code Playgroud)
当然不行,这行不通。您仍然需要括号:
int bar=foo();
Run Code Online (Sandbox Code Playgroud)
模板也是如此。