gpt4 book ai didi

c++ - 具有隐式转换的模板函数参数推导

转载 作者:行者123 更新时间:2023-11-30 01:39:27 24 4
gpt4 key购买 nike

我了解模板函数参数推导不考虑隐式转换。

所以这段代码无法编译:

#include <iostream>

template<class T>
struct A {};
struct B : public A<int> {};
struct C {
operator B() { return {}; }
};

template<class X>
void test(A<X> arg1, A<X> arg2) {
std::cout << "ok1";
}

int main() {
B b;
C c;
test(b, c); // error: no matching function for call to 'test'
}

我不明白的是如何使用identity typedef 添加额外的间接级别 以某种方式使它起作用:

#include <iostream>

template<class T>
struct A {};
struct B : public A<int> {};
struct C {
operator B() { return {}; }
};

template<typename U> struct magic { typedef U type; };

template<class T> using magic_t = typename magic<T>::type;

template<class X>
void test(A<X> arg1, A<X> arg2) {
std::cout << "ok1";
}

template<class X>
void test(A<X> arg3, magic_t<A<X>> arg4) {
std::cout << "ok2";
}

int main() {
B b;
C c;
test(b, c); // prints "ok2"
}

Live demo on Godbolt

如何magic_t<A<X>>最终匹配C

最佳答案

第二个参数变为non-deduced context并且不参与模板参数推导。 X 然后从第一个参数成功推导出来。

关于c++ - 具有隐式转换的模板函数参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45765205/

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