需要同时具备const与非const重载的概念

人工智能 2026-07-11

我如何编写一个概念,使得只有当某个类对给定成员函数同时具有带const限定的重载和非const限定的重载时才成立?

Google给了我一些AI给出的无用建议,根本行不通;如果尝试把const与非const成员函数的两个概念组合起来,也行不通。
原因显然是 HasNonConstFoo 也接受 const 的重载,而它本不应该这么做;然而,如果我把它改成拒绝const重载,我就看不到如何把它与另一个概念结合起来。

Godbolt: https://godbolt.org/z/6hq6zeneK

#include <print>
#include <concepts>
#include <utility>

template <typename T>
concept HasNonConstFoo = requires (T non_const_val) {
  //must be altered somehow to reject const overloads
    { non_const_val.foo() } -> std::same_as<void>;
};

template <typename T>
concept HasConstFoo = requires(const T const_val) {
  { const_val.foo() } -> std::same_as<void>;
};

template <typename T> 
concept Both = HasNonConstFoo<T> && HasConstFoo<T>;

// Example Class with both const && non const
struct MyClass {
    void foo() { std::puts("Non-const foo()\n"); }

    void foo() const { std::puts("Const foo()\n"); }
};


struct NonConstOnly {
    void foo() { std::puts("Non-const foo()\n"); }
};

struct ConstOnly {
    void foo() const { std::puts("Const foo()\n"); }
};

template <Both T>
void call_foo(T& obj) {
    obj.foo();         
    const T& const_obj = obj;
    const_obj.foo();    
}

int main() {
    MyClass mc;
    call_foo(mc); // Compiles fine

    //NonConstOnly nco;
    //call_foo(nco); // Fails compilation: missing const foo()

    ConstOnly co;
    call_foo(co); // Should Fail compilation: but doesn't
}

我如何得到一个需要同时存在const与非const重载的概念?

解决方案

我将通过比较签名来推进,而不测试调用的有效性(当存在 const 版本时,这种做法会正确地无法检测到缺失的非 const 版本):

template <typename T, typename out,typename ...in>
concept HasNonConstFoo =
    requires { static_cast<out (T::*)(in...)>(&T::foo); };

template <typename T, typename out,typename ...in>
concept HasConstFoo =
    requires { static_cast<out (T::*)(in...) const>(&T::foo); };

template <typename T, typename out,typename ...in>
concept Both = HasNonConstFoo<T,out,in...> && HasConstFoo<T,out,in...>;

LIVE 使用模板成员函数
LIVE 不使用

Note: 它还允许选择期望的返回类型和参数类型。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章