C++ 有一个有用的功能,即模板参数隐含在模板类内的代码中A
。
然而,对于建筑来说,这似乎与 CTAD 发生冲突。
如何让 CTAD 优先?
例如,这里有一个错误f
会员因为A
被解释为A<T>
where T
is std::string
,并且不是从参数推导出来的double
.
#include<string>
template<class T>
struct A {
A(T const& t) {}
auto f() {return A{5.0};} // error here triggered by line 11 `auto a2 = a1.f();`
};
int main() {
A a1{std::string{"hello"}};
auto a2 = a1.f();
}
https://godbolt.org/z/3nc7nev3o https://godbolt.org/z/3nc7nev3o
你需要使用::A
告诉编译器使用该名称A
来自全局范围而不是使用名称A
在类范围内,这只是简写A<T>
。这给你:
#include<string>
template<class T>
struct A {
A(T const& t) {}
auto f() {return ::A{5.0};} // uses CTAD to return A<double>
};
int main() {
A a1{std::string{"hello"}};
auto a2 = a1.f();
}
正如在这个中看到的活生生的例子 https://godbolt.org/z/rcjMGTj73.
另一种选择是向类类型添加私有别名,然后根据需要在函数中使用该别名。这给你:
#include<string>
template<class T>
struct A {
private:
template <typename U>
using NewA = A<U>;
public:
A(T const& t) {}
auto f() {return NewA{5.0};} // uses CTAD to return A<double>
};
int main() {
A a1{std::string{"hello"}};
auto a2 = a1.f();
}
可以看到工作here https://godbolt.org/z/rKr96sed8
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)