【问题标题】:Nested template argument deduction嵌套模板参数推导
【发布时间】:2022-11-01 20:30:12
【问题描述】:

我有一些以输出类型为模板的函数。然后,此函数接受一个输入参数,该参数又以输出类型为模板。我不想指定输出类型两次,因为这只会使 api 混乱。在我的世界里,我已经告诉编译器它需要知道的一切来正确推断这一点,但我无法让它工作。建议?

template<typename T>
struct TestStruct {};


template<typename T, template<typename> class U>
T testFunc(U<T> arg)
{
  return T{0};   
}

int main()
{
    testFunc<double>(TestStruct<double>{}); // Compiles
    testFunc<double>(TestStruct{});         // Does not compile  
}

【问题讨论】:

  • testFunc(TestStruct&lt;double&gt;{}); 有什么问题?第二行的问题是该函数采用U&lt;T&gt;,而您只提供U,它本身不是一个类型。

标签: c++ template-meta-programming


【解决方案1】:

问题不是testFunc,而是TestStruct{},因为您没有传递模板参数,并且类模板TestStruct 的相应模板参数没有默认参数。


我不想指定输出类型两次

因为您只想指定 double 一次,您可以这样做:

template<typename T, template<typename> class U>
T testFunc(U<T> arg)
{
  return T{0};   
}

int main()
{
//----------------------vvvvvv-------------->only once as you want   
    testFunc(TestStruct<double>{});
//----------^------------------------------->no need to specify double here as it can be deduced   
}

Demo

如上面修改后的程序所示,当将double 作为TestStruct 的模板参数传递时,我们只指定了一次。可以推导出函数模板testFuncT的模板参数。

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 2019-06-04
    • 2023-03-24
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多