You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于类模板参数启用成员函数重载(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:22:48