在自己的成员函数中构造类时,如何强制类模板参数推导? [英] How to force class template argument deduction when constructing a class in its own member functions?

查看:67
本文介绍了在自己的成员函数中构造类时,如何强制类模板参数推导?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

struct A {};

template <typename T> struct B
{
    B(T) {}
    auto foo() {return B(A{});} // error: no matching function for call to 'B<int>::B(A)'
};

auto foo() {return B(A{});} // compiles

int main()
{
    foo();
    B b(0);
    b.foo();
}

立即尝试

我理解为什么 B :: foo( )无法编译:在 struct B< T> B 中(如除非明确将其用作模板,否则表示 B< T>

I understand why B::foo() doesn't compile: Inside of struct B<T>, B (as an injected-class-name) means B<T> unless it's explicitly used as a template. Which in this case prevents class template argument deduction.

让我们说我不能做 auto foo(){返回B< A>(A {});} ,因为我的实际代码依赖于用户提供的精心制作的推导指南。

Let's say I can't do auto foo() {return B<A>(A{});} since my actual code relies on slightly elaborate user-provided deduction guides.

问题是:如何强制上课在 B :: foo 内构造 B 时的模板参数推导?

The question is: How do I force class template argument deduction when constructing B inside of B::foo?

我希望我不会缺少明显的东西。

推荐答案

您有资格这样做

auto foo() {return ::B(A{});}

这篇关于在自己的成员函数中构造类时,如何强制类模板参数推导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆