gpt4 book ai didi

c++ - 模板参数替换失败,并且未完成隐式转换

转载 作者:行者123 更新时间:2023-12-02 10:05:27 25 4
gpt4 key购买 nike

#include <type_traits>

template<bool Const>
struct view_tpl {
using value_type = std::conditional_t<Const, const int, int>;
value_type* ptr;

view_tpl() = default;
view_tpl(const view_tpl<false>& other) : ptr(other.ptr) { }
};

using view = view_tpl<false>;
using const_view = view_tpl<true>;

void read(const const_view& vw) { }

int main() {
view vw;
read(vw);
}

此代码定义const和非const View 类型,它们都是 view_tpl<Const>模板的别名。应该将 view隐式转换为 const_view,但不能反过来。

它的 Consttrue,定义的copy-constructor启用了此功能,并且编译器生成了另一个默认的copy-constructor。如果 Constfalse,则定义的复制构造函数将替换默认的复制构造函数。

调用 f(vw)时应该发生这种隐式转换。

在上面的代码中它可以正常工作。

但是,如果我向模板( int N)添加参数,然后将 f和两个类型别名转换为模板,则该模板将不再起作用:
#include <type_traits>

template<int N, bool Const>
struct view_tpl {
using value_type = std::conditional_t<Const, const int, int>;
value_type* ptr;

view_tpl() = default;
view_tpl(const view_tpl<N, false>& other) : ptr(other.ptr) { }
};

template<int N> using view = view_tpl<N, false>;
template<int N> using const_view = view_tpl<N, true>;

template<int N>
void read(const const_view<N>& vw) { }

int main() {
view<0> vw;
read(vw);
}

编译器不尝试将 view_tpl<0, true>转换为 view_tpl<0, false>,而是仅尝试直接模板替换并失败:
main.cpp: In function 'int main()':
main.cpp:20:12: error: no matching function for call to 'read(view<0>&)'
20 | read(vw);
| ^
main.cpp:16:6: note: candidate: 'template<int N> void read(const_view<N>&)'
16 | void read(const const_view<N>& vw) { }
| ^~~~
main.cpp:16:6: note: template argument deduction/substitution failed:
main.cpp:20:12: note: template argument 'false' does not match 'true'
20 | read(vw);
| ^

有没有办法在不更改太多代码的情况下完成这项工作? (实际代码比此示例更复杂)

最佳答案

不幸的是,template argument deduction不会考虑隐式转换。

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.



您可以显式指定模板参数,以通过推导,然后隐式转换将在以后正常工作。例如
view<0> vw;
read<0>(vw);

或应用显式转换并将其包装到帮助器中。
template<int N>
void read(const view<N>& vw) { read(static_cast<const_view<N>>(vw)); }

关于c++ - 模板参数替换失败,并且未完成隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60410602/

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