自从
C++17
起,你可以使用占位符类型(
auto
和
decltype(auto)
)作为
非类型模板参数的类型。这意味着我们可以写出泛型代码来处理不同类型的非类型模板参数。
使用auto
模板参数
自从C++17
起,你可以使用auto
来声明非类型模板参数。例如:
#include <iostream>
using namespace std;
template<auto N> struct S {
S(){cout <<" S Constructor " << N <<endl;}
};
这允许我们为不同类型实例化非类型模板参数N
:
int main() {
S<42> s1; // OK:S中N的类型是int
S<'A'> s2;// OK:S中N的类型是char
}
运行结果如下:
S Constructor 42
S Constructor A
预处理代码如下:
#include <iostream>
using namespace std;
template<auto N>
struct S
{
inline S()
{
operator<<(operator<<(std::operator<<(std::cout, " S Constructor "), N), endl);
}
};
/* First instantiated from: insights.cpp:10 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct S<42>
{
inline S()
{
std::operator<<(std::cout, " S Constructor ").operator<<(42).operator<<(std::endl);
}
};
#endif
/* First instantiated from: insights.cpp:11 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct S<'A'>
{
inline S()
{
std::operator<<(std::operator<<(std::cout, " S Constructor "), 'A').operator<<(std::endl);
}
};
#endif
int main()
{
S<42> s1 = S<42>();
S<'A'> s2 = S<'A'>();
return 0;
}
然而,你不能使用这个特性来实例化一些不允许作为模板参数的类型:
S<2.5> s3; // ERROR:模板参数的类型不能是double
我们甚至还可以用指明类型的版本作为部分特化版:
template<int N> class S<N> {};
示例代码如下:
#include <iostream>
using namespace std;
template <auto N>
struct S {
S() { cout << " S Constructor " << N << endl; }
};
template<long N> struct S<N> {
S() { cout << " S Constructor special " << N << endl; }
};
int main() {
S<42> s1;
S<'A'> s2;
S<42l> s3;
}
甚至还支持类模板参数推导。例如:
template<typename T, auto N>
class A {
public:
A(const std::array<T, N>&) {
}
A(T(&)[N]) {
}
...
};
这个类可以推导出T
的类型、N
的类型、N
的值:
A a2{"hello"}; // OK,推导为A<const char, 6>,N的类型是std::size_t
std::array<double, 10> sa1;
A a1{sa1}; // OK,推导为A<double, 10>,N的类型是std::size_t
预处理代码如下:
#include <array>
#include <iostream>
using namespace std;
template<typename T, auto N>
class A
{
public:
inline A(const std::array<T, N> &)
{
}
inline A(T (&)[N])
{
}
};
/* First instantiated from: insights.cpp:13 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class A<const char, 6>
{
public:
inline A(const std::array<const char, 6> &);
inline A(const char (&)[6])
{
}
};
#endif
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class A<double, 10>
{
public:
inline A(const std::array<double, 10> &)
{
}
inline A(double (&)[10]);
};
#endif
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
A(const std::array<double, 10> &) -> A<double, 10>;
#endif
/* First instantiated from: insights.cpp:13 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
A(const char (&)[6]) -> A<const char, 6>;
#endif
int main()
{
A<const char, 6> a2 = A<const char, 6>{"hello"};
std::array<double, 10> sa1 = std::array<double, 10>();
A<double, 10> a1 = A<double, 10>{sa1};
return 0;
}
你也可以修饰auto
,例如,可以确保参数类型必须是个指针:
非类型模板参数可以是指针,但该指针必须指向外部链接对象,此项使用的详细解释
template<const auto* P> struct S; //
另外,通过使用可变参数模板,你可以使用多个不同类型的模板参数来实例化模板:
template<auto... VS> class HeteroValueList {
};
也可以用多个相同类型的参数:
template<auto V1, decltype(V1)... VS> class HomoValueList {
};
完整示例如下:
#include <array>
#include <iostream>
using namespace std;
template <const auto* P>
struct S {
S() { cout << "S = " << (P) << endl; }
};
template <auto... VS>
class HeteroValueList {
public:
HeteroValueList() { cout << "HeteroValueList = " << (... + VS) << endl; }
};
template <auto V1, decltype(V1)... VS>
class HomoValueList {
public:
HomoValueList() {
cout << "HomoValueList V1= " << V1 << " other = " << (... + VS) << endl;
}
};
int main() {
static char str1[] = "Test 1";
S<str1> x;
HeteroValueList<1, 2, 3> vals1; // OK
HeteroValueList<1, 'a', true> vals2; // OK
HomoValueList<1, 2, 3> vals3; // OK
HomoValueList<1, 'a', 3> vals4; // OK
}
运行结果如下:
S = Test 1
HeteroValueList = 6
HeteroValueList = 99
HomoValueList V1= 1 other = 5
HomoValueList V1= 1 other = 100
预编译代码如下:
#include <array>
#include <iostream>
using namespace std;
template<const auto * P>
struct S
{
inline S()
{
operator<<(operator<<(std::operator<<(std::cout, "S = "), (P)), endl);
}
};
/* First instantiated from: insights.cpp:26 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct S<&str1>
{
inline S()
{
std::operator<<(std::operator<<(std::cout, "S = "), (str1)).operator<<(std::endl);
}
};
#endif
template<auto ...VS>
class HeteroValueList
{
public:
inline HeteroValueList()
{
operator<<(operator<<(std::operator<<(std::cout, "HeteroValueList = "), (... + VS)), endl);
}
};
/* First instantiated from: insights.cpp:27 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class HeteroValueList<1, 2, 3>
{
public:
inline HeteroValueList()
{
std::operator<<(std::cout, "HeteroValueList = ").operator<<((1 + 2) + 3).operator<<(std::endl);
}
};
#endif
/* First instantiated from: insights.cpp:28 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class HeteroValueList<1, 'a', true>
{
public:
inline HeteroValueList()
{
std::operator<<(std::cout, "HeteroValueList = ").operator<<((1 + static_cast<int>('a')) + static_cast<int>(true)).operator<<(std::endl);
}
};
#endif
template<auto V1, decltype(V1) ...VS>
class HomoValueList
{
public:
inline HomoValueList()
{
operator<<(operator<<(operator<<(operator<<(std::operator<<(std::cout, "HomoValueList V1= "), V1), " other = "), (... + VS)), endl);
}
};
/* First instantiated from: insights.cpp:29 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class HomoValueList<1, 2, 3>
{
public:
inline HomoValueList()
{
std::operator<<(std::operator<<(std::cout, "HomoValueList V1= ").operator<<(1), " other = ").operator<<(2 + 3).operator<<(std::endl);
}
};
#endif
/* First instantiated from: insights.cpp:30 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class HomoValueList<1, 97, 3>
{
public:
inline HomoValueList()
{
std::operator<<(std::operator<<(std::cout, "HomoValueList V1= ").operator<<(1), " other = ").operator<<(97 + 3).operator<<(std::endl);
}
};
#endif
int main()
{
static char str1[7] = "Test 1";
S<&str1> x = S<&str1>();
HeteroValueList<1, 2, 3> vals1 = HeteroValueList<1, 2, 3>();
HeteroValueList<1, 'a', true> vals2 = HeteroValueList<1, 'a', true>();
HomoValueList<1, 2, 3> vals3 = HomoValueList<1, 2, 3>();
HomoValueList<1, 97, 3> vals4 = HomoValueList<1, 97, 3>();
return 0;
}
字符和字符串模板参数
可以定义一个既可能是字符也可能是字符串的模板参数。例如,我们可以像下面这样改进用折叠表达式输出任意数量参数的方法:
#include <iostream>
template<auto Sep = ' ', typename First, typename... Args>
void print(const First& first, const Args&... args) {
std::cout << first;
auto outWithSep = [] (const auto& arg) {
std::cout << Sep << arg;
};
(... , outWithSep(args));
std::cout << '\n';
}
将默认的参数分隔符Sep
设置为空格,我们可以实现和之前相同的效果:
template<auto Sep = ' ', typename First, typename... Args>
void print(const First& firstarg, const Args&... args) {
...
}
我们仍然可以像之前一样调用:
std::string s{"world"};
print(7.5, "hello", s); // 打印出:7.5 hello world
然而,通过把分隔符Sep
参数化,我们也可以显示指明另一个字符作为分隔符:
print<'-'>(7.5, "hello", s); // 打印出:7.5-hello-world
甚至,因为使用了auto
,我们甚至可以传递被声明为无链接的字符串字面量作为分隔符:
static const char sep[] = ", ";
print<sep>(7.5, "hello", s); // 打印出:7.5, hello, world
另外,我们也可以传递任何其他可以用作模板参数的类型:
print<-11>(7.5, "hello", s); // 打印出:7.5-11hello-11world
定义元编程常量
定义编译期常量的更加容易。
原本的下列代码:
template<typename T, T v>
struct constant
{
static constexpr T value = v;
};
using i = constant<int, 42>;
using c = constant<char, 'x'>;
using b = constant<bool, true>;
现在可以简单的实现为:
template<auto v>
struct constant
{
static constexpr auto value = v;
};
using i = constant<42>;
using c = constant<'x'>;
using b = constant<true>;
完整示例:
#include <array>
#include <iostream>
using namespace std;
template <auto v>
struct constant {
static constexpr auto value = v;
};
using i = constant<42>;
using c = constant<'x'>;
using b = constant<true>;
int main() {
i jj;
c jj1;
b jj2;
}
预处理代码如下:
#include <array>
#include <iostream>
using namespace std;
template<auto v>
struct constant
{
inline static constexpr const auto value = v;
};
/* First instantiated from: insights.cpp:14 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct constant<42>
{
inline static constexpr const int value = 42;
// inline constexpr constant() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct constant<'x'>
{
inline static constexpr const char value = 'x';
// inline constexpr constant() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:16 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct constant<true>
{
inline static constexpr const bool value = true;
// inline constexpr constant() noexcept = default;
};
#endif
using i = constant<42>;
using c = constant<'x'>;
using b = constant<true>;
int main()
{
constant<42> jj = constant<42>();
constant<'x'> jj1 = constant<'x'>();
constant<true> jj2 = constant<true>();
return 0;
}
同样,原本的下列代码:
template<typename T, T... Elements>
struct sequence {
};
using indexes = sequence<int, 0, 3, 4>;
现在可以简单的实现为:
template<auto... Elements>
struct sequence {
};
using indexes = sequence<0, 3, 4>;
预处理代码如下:
template<typename T, T ...Elements>
struct sequence
{
};
/* First instantiated from: insights.cpp:11 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct sequence<int, 0, 3, 4>
{
// inline constexpr sequence() noexcept = default;
};
#endif
using indexes = sequence<int, 0, 3, 4>;
int main()
{
sequence<int, 0, 3, 4> i = sequence<int, 0, 3, 4>();
return 0;
}
你现在甚至可以定义一个持有若干不同类型的值的编译期对象(类似于一个简单的tuple
):
using tuple = sequence<0, 'h', true>;
使用auto
作为变量模板的参数
你也可以使用auto
作为模板参数来实现 变量模板(variable templates) 。
例如,下面的声明定义了一个变量模板arr
,它的模板参数分别是元素的类型和数量:
template<typename T, auto N> std::array<T, N> arr;
在每个编译单元中,所有对arr<int, 10>
的引用将指向同一个全局对象。而arr<long, 10>
和arr<int, 10u>
将指向其他对象(每一个都可以在所有编译单元中使用)。作为一个完整的例子,考虑如下的头文件:
#ifndef VARTMPLAUTO_HPP
#define VARTMPLAUTO_HPP
#include <array>
template<typename T, auto N> std::array<T, N> arr{};
void printArr();
#endif // VARTMPLAUTO_HPP
这里,我们可以在一个编译单元内修改两个变量模板的不同实例:
#include "vartmplauto.hpp"
int main()
{
arr<int, 5>[0] = 17;
arr<int, 5>[3] = 42;
arr<int, 5u>[1] = 11;
arr<int, 5u>[3] = 33;
printArr();
}
另一个编译单元内可以打印这两个变量模板:
#include "vartmplauto.hpp"
#include <iostream>
void printArr()
{
std::cout << "arr<int, 5>: ";
for (const auto& elem : arr<int, 5>) {
std::cout << elem << ' ';
}
std::cout << "\narr<int, 5u>: ";
for (const auto& elem : arr<int, 5u>) {
std::cout << elem << ' ';
}
std::cout << '\n';
}
程序的输出将是:
arr<int, 5>: 17 0 0 42 0
arr<int, 5u>: 0 11 0 33 0
用同样的方式你可以声明一个任意类型的常量变量模板,类型可以通过初始值推导出来:
template<auto N> constexpr auto val = N; // 自从C++17起OK
之后可以像下面这样使用:
auto v1 = val<5>; // v1 == 5,v1的类型为int
auto v2 = val<true>; // v2 == true,v2的类型为bool
auto v3 = val<'a'>; // v3 == 'a',v3的类型为char
这里解释了发生了什么:
std::is_same_v<decltype(val<5>), int> // 返回false
std::is_same_v<decltype(val<5>), const int> // 返回true
std::is_same_v<decltype(v1), int> // 返回true(因为auto会退化)
使用decltype(auto)
模板参数
你现在也可以使用另一个占位类型decltype(auto)
(C++14
引入)作为模板参数。注意,这个占位类型的推导有非常特殊的规则。根decltype
的规则,如果使用decltype(auto)
来推导 表达式(expressions) 而不是变量名,那么推导的结果将依赖于表达式的值类型:
- prvalue(例如临时变量)推导出 type
- lvalue(例如有名字的对象)推导出 type&
- xvalue(例如用
std::move()
标记的对象)推导出 type&&
这意味着你很容易就会把模板参数推导为引用,这可能导致一些令人惊奇的效果。
例如:
#include <iostream>
template<decltype(auto) N>
struct S {
void printN() const {
std::cout << "N: " << N << '\n';
}
};
static const int c = 42;
static int v = 42;
int main()
{
S<c> s1; // N的类型推导为const int 42
S<(c)> s2; // N的类型推导为const int&,N是c的引用
s1.printN();
s2.printN();
S<(v)> s3; // N的类型推导为int&,N是v的引用
v = 77;
s3.printN(); // 打印出:N: 77
}
运行结果如下;
N: 42
N: 42
N: 77
预处理代码如下:
#include <iostream>
template<decltype(auto) N>
struct S
{
inline void printN() const
{
(std::operator<<(std::cout, "N: ") << N) << '\n';
}
};
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct S<42>
{
inline void printN() const
{
std::operator<<(std::operator<<(std::cout, "N: ").operator<<(42), '\n');
}
// inline constexpr S() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:16 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct S<&c>
{
inline void printN() const
{
std::operator<<(std::operator<<(std::cout, "N: ").operator<<(c), '\n');
}
// inline constexpr S() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:20 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
struct S<&v>
{
inline void printN() const
{
std::operator<<(std::operator<<(std::cout, "N: ").operator<<(v), '\n');
}
// inline constexpr S() noexcept = default;
};
#endif
static const int c = 42;
static int v = 42;
int main()
{
S<42> s1 = S<42>();
S<&c> s2 = S<&c>();
s1.printN();
s2.printN();
S<&v> s3 = S<&v>();
v = 77;
s3.printN();
return 0;
}