gpt4 book ai didi

c++ - 基于依赖类型的存在重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:39 24 4
gpt4 key购买 nike

我有两个同名的模板函数 (foo)。它们的签名仅在第二个参数的类型上有所不同,这取决于模板参数 T。令我感到惊讶的是,我可以根据 T::AT::B 是否存在类型来使用它来重载。这是标准中专门提供的东西吗(如果是这样,将不胜感激),还是我只是太过拘泥于没有将其识别为基本的重载解决方案?

#include <iostream>
using namespace std;

template<typename T>
void foo(T t, typename T::A* a = 0) {
cout << "Had an A" << endl;
}

template<typename T>
void foo(T t, typename T::B* b = 0) {
cout << "Had a B" << endl;
}

struct HasAnAType {
typedef int A;
};

struct HasABType {
typedef int B;
};

struct HasAAndBTypes {
typedef int A;
typedef int B;
};

int main() {
HasAnAType a;
HasABType b;
HasAAndBTypes ab;

foo(a); // prints "Had an A"
foo(b); // prints "Had a B"
foo(ab); // won't compile: 'ambiguous call to overloaded function'
}

作为背景,我在研究 std::enable_shared_from_this 的实现时发现这是可能的,它依赖于这种类型的重载。

最佳答案

感谢SFINAE ,重载 void foo(T t, typename T::B* b = 0)T::B 不存在时被移除存在(类似于 T::A)

所以当两者都可用时,两个重载都是可行的,因此调用是不明确的。

关于c++ - 基于依赖类型的存在重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com