如何基于类模板参数启用成员函数重载(C++20 Concepts)
解决方案
你的代码问题在于,当T为int时,两个operator=重载的签名完全相同,且第二个重载无约束限制,会和第一个重载产生冲突(编译器无法区分)。要实现基于类模板参数的重载选择,只需给第二个重载也加上互斥的requires约束,确保任意T下只有一个重载生效:
#include <concepts> #include <iostream> template <typename T> struct entity { requires std::same_as<T, int> auto operator=(const entity&) { std::cout << "with T == int" << std::endl; return *this; } requires (!std::same_as<T, int>) auto operator=(const entity&) { std::cout << "all else" << std::endl; return *this; } };
原理说明
- 当
T是int时,第一个重载的约束满足,第二个的约束不满足,仅第一个重载被实例化; - 当
T不是int时,第二个重载的约束满足,第一个的约束不满足,仅第二个重载被实例化; - 该方案无需给函数添加额外模板参数,完全通过类模板参数
T和互斥的requires约束实现重载选择。
内容的提问来源于stack exchange,提问作者glades
相关产品推荐
相关产品推荐

