gpt4 book ai didi

c++ - 为什么我们不能在内联命名空间之外声明演绎指南?

转载 作者:行者123 更新时间:2023-12-01 13:30:13 25 4
gpt4 key购买 nike

例子:

namespace X{
inline namespace Y{
template<typename T>
struct A{
};
}
}
namespace X{
template<typename Z>
A(std::vector<Z>) -> A<Z>;
}
这会导致 Clang 11 中出现编译错误,其中显示“演绎指南必须在与模板 X::Y::A 相同的范围内声明”
与模板特化类似,推导指南也应在与类模板相同的语义范围内声明。 那么为什么我可以在内联命名空间之外专门化类模板,但对于推导指南我不能?
特别是,这会导致另一个问题:
template<typename T>
struct Q{
operator std::vector<T>() {
return {};
}
};

namespace std{
template<typename T>
vector(Q<T>) -> vector<T>;
}
如果我想定义一个转换为 std::vector 的类模板,编译器会拒绝并为其申报扣除指南。在这种情况下(对于 libc++),我必须在 namespace std::__1 中声明它.
CPP标准中是否有一些解决方案或解释?

最佳答案

so why I can specialize the class template outside the inline namespace, but for deduction guide I can't?


因为你可以专门化模板。来自 C++ 标准 [namespace.def]/7 :

Members of an inline namespace can be used in most respects as though they were members of the enclosing namespace. Specifically, the inline namespace and its enclosing namespace are both added to the set of associated namespaces used in argument-dependent lookup whenever one of them is, and a using-directive that names the inline namespace is implicitly inserted into the enclosing namespace as for an unnamed namespace.Furthermore, each member of the inline namespace can subsequently be partially specialized, explicitly instantiated, or explicitly specialized as though it were a member of the enclosing namespace


对于演绎指南,它需要与类模板在同一范围内。来自标准 [temp.deduct.guide]/3 :

[...] A deduction-guide shall be declared in the same scope as the corresponding class template and, for a member class template, with the same access. [...]


解决方案是明确给出 X::Y范围:
namespace X::inline Y{
template<typename Z>
A(std::vector<Z>) -> A<Z>;
}

关于c++ - 为什么我们不能在内联命名空间之外声明演绎指南?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63393829/

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