只是好奇:在 C++17 及更高版本中,我们可以对非类型模板参数使用 auto
占位符:
template<typename A, auto B>
class C {
public:
A foo() { return B; }
};
但是我们可以传递模板类型参数 A
而不是 auto
吗?
示例.cpp
template<typename A, A B>
class C {
public:
A foo() { return B; }
};
int main()
{
C<int, 5> c;
std::cout << c.foo() << std::endl;
return 0;
}
实际上我们可以,并且 clang with -std=c++11 允许这样做。
$ g++ -std=c++11 example.cpp
$ ./a.out
5
但是标准呢?我没有找到任何明确的规则。 谢谢!
最佳答案
当然。这是老方法。But can we pass instead of "auto" template type parameter defined at left?
但是auto
方式允许避免传递类型A
。
在 C++17 中你可以这样写
template <auto B>
class C {
public:
auto foo() { return B; }
};
因此不需要传递类型A
。
我不知道如何在 C++11/C++14 中执行相同操作。
我的意思是:如果你愿意,在 C++11/C++14 中将值传递给模板...如果类型是固定的,那就没有问题
template <int I>
但类型本身可以不同,在 C++11/C++14 中,您必须首先传递类型,然后传递值,如 example.cpp 中所示
template <typename T, T A>
问题是,按照旧的方式,如果你想调用那种类型的模板,你必须是多余的,并写一些东西
C<decltype(x), x> some_C_variable;
我知道避免这种冗余的唯一方法是通过 make 函数(类似于 make_tuple()
)或 C 风格的宏。
在 C++17 中你可以简单地写
C<x> some_C_variable
并且,在 C 模板类/结构内部,可以从 decltype(B)
获取 x
的类型。
对于 C++17 标准引用...
首先,auto
被定义为“placeolder”
从 10.1.7.4(auto
说明符)开始,第 1 点
The
auto
anddecltype(auto)
type-specifiers are used to designate a placeholder type that will be replaced later by deduction from an initializer.
在 C++11/C++14 中也是如此
但C++17标准添加,对于“模板参数”(17.1),在第4点枚举中,新点4.6
- A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
[...]
(4.6) a type that contains a placeholder type (10.1.7.4)
关于c++ - 将模板类型参数作为模板非类型参数的类型传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427361/