在C++模板开发中,经常会遇到需要模板参数类型具备特定成员函数的场景,比如要求传入的类型必须有serialize成员函数才能完成序列化操作。C++20推出的concepts特性可以非常直观地实现这类约束,避免模板实例化时出现难以理解的错误信息。

concepts基础语法回顾
concept是C++20新增的特性,用于定义对类型的要求,本质是编译期的谓词,用来约束模板参数的类型。基本定义语法如下:
// 定义一个concept,要求类型T必须有名为func的成员函数,且接受int参数,返回void
template <typename T>
concept HasSpecificFunc = requires(T t, int arg) {
{ t.func(arg) } -> std::same_as<void>;
};
上面的requires表达式是concept的核心,用来描述对类型的具体要求,std::same_as是标准库提供的concept,用来检查两个类型是否相同。
约束模板函数参数必须有指定成员函数
假设我们需要实现一个模板函数process,要求传入的参数类型必须有一个execute成员函数,该函数不接受参数,返回int类型。我们可以按照以下步骤实现:
第一步:定义对应的concept
首先定义约束类型必须包含execute成员函数的concept:
#include <concepts>
// 定义concept,要求类型T有execute成员函数,无参数,返回int
template <typename T>
concept HasExecute = requires(T t) {
{ t.execute() } -> std::same_as<int>;
};
第二步:使用concept约束模板函数
有两种常见的方式将concept应用到模板函数上:
方式一:使用requires子句
#include <iostream>
// 模板函数,使用requires子句约束T必须满足HasExecute concept
template <typename T>
requires HasExecute<T>
int process(T obj) {
return obj.execute();
}
方式二:使用concept作为类型约束
// 更简洁的写法,直接将concept放在类型参数位置作为约束
template <HasExecute T>
int process(T obj) {
return obj.execute();
}
验证约束效果
我们定义两个类型,一个符合约束,一个不符合,测试模板函数的调用情况:
// 符合约束的类型,有execute成员函数,返回int
struct ValidType {
int execute() {
std::cout << "ValidType execute called" << std::endl;
return 100;
}
};
// 不符合约束的类型,没有execute成员函数
struct InvalidType {
void run() {
std::cout << "InvalidType run called" << std::endl;
}
};
int main() {
ValidType v;
process(v); // 正常调用,输出ValidType execute called
InvalidType inv;
// process(inv); // 编译报错,提示InvalidType不满足HasExecute约束
return 0;
}
当传入不符合约束的类型时,编译器会直接提示类型不满足concept要求,错误信息比SFINAE方式清晰很多。
约束成员函数的更多场景
除了约束成员函数的存在和返回类型,还可以约束成员函数的参数类型、是否为const成员函数等:
#include <string>
#include <concepts>
// 约束类型T有const的print成员函数,接受std::string参数,返回void
template <typename T>
concept HasConstPrint = requires(const T t, std::string s) {
{ t.print(s) } -> std::same_as<void>;
};
struct Test {
void print(std::string s) const {
std::cout << s << std::endl;
}
};
// 使用约束的模板函数
template <HasConstPrint T>
void call_print(const T& obj, std::string msg) {
obj.print(msg);
}
concepts相比传统方式的优势
- 语法更直观,约束条件直接写在代码里,可读性远高于SFINAE的复杂模板元编程写法
- 编译错误信息更友好,直接提示类型不满足哪个约束条件,方便定位问题
- 可以复用concept,多个模板函数可以共用同一个concept约束,减少重复代码
- 支持组合多个concept,通过
&&和||运算符组合约束条件,比如HasExecute && std::copyable表示类型既要满足成员函数约束,也要可拷贝
使用concepts约束模板函数参数必须具有某成员函数,是C++20之后模板编程的推荐做法,能够大幅提升代码的质量和可维护性。