【问题标题】:How to force class template argument deduction when constructing a class in its own member functions?在自己的成员函数中构造类时如何强制类模板参数推导?
【发布时间】:2018-08-08 19:52:22
【问题描述】:

考虑以下代码:

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();
}

Try it live

我明白为什么B::foo() 不能编译:struct B&lt;T&gt; 内部,B(作为注入的类名)意味着B&lt;T&gt;,除非它被明确用作模板。在这种情况下,它可以防止类模板参数推导。

假设我做不到auto foo() {return B&lt;A&gt;(A{});},因为我的实际代码依赖于稍微复杂的用户提供的推导指南。

问题是:在B::foo 内部构造B 时,如何强制类模板参数推导?

我希望我没有遗漏一些明显的东西。

【问题讨论】:

  • ::B(A{})? ---

标签: c++ c++17


【解决方案1】:

您对其进行限定,使其不是注入的类名。

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

【讨论】:

    【解决方案2】:

    另一种选择是使用函数为您进行类型推导。

    template <typename T> B<T> make_b(T t) { return B<T>(t); }
    

    并使用

    auto foo() {return make_b(A{});} 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2021-10-25
      • 2016-02-17
      相关资源
      最近更新 更多