【问题标题】:How to invoke the template function in a loop manner?如何循环调用模板函数?
【发布时间】:2020-10-07 02:00:49
【问题描述】:

这个问题主要是关于设计方法的,我想知道如何用现代C++语言解决这类问题。

我有一个定义如下的库函数(这是来自编译器的真实代码):

template <info::device param>
typename info::param_traits<info::device, param>::return_type
get_info() const;

为了调用这个函数,我可以这样写:

some_device.get_info<cl::sycl::info::device::device_type>()

其中cl::sycl::info::device::device_type 是一个实际参数。

支持的参数列表很长,我想要一组结果值(不同函数调用的结果)。

此时,我可以这样做:

some_device.get_info<cl::sycl::info::device::param1>()
some_device.get_info<cl::sycl::info::device::param2>()
...
some_device.get_info<cl::sycl::info::device::paramN>()

但是因为这很糟糕,我正在 C++ 11/14 中寻找更好的解决方案。

【问题讨论】:

  • 由于返回类型似乎取决于模板参数(不同参数可能不同),您会将返回值存储在哪个集合中?
  • @HolyBlackCat 我想先将所有返回值转换为std::string,并将其存储在相应的集合中。
  • info::device_type 如何匹配 &lt;info::device param&gt; ?你是说info::device::device_type 吗?
  • @PiotrSkotnicki device 可能是一个普通的(无范围的)enum
  • 可能类似于template &lt;info::device... Params&gt; std::vector&lt;std::string&gt; f() { return {to_string(some_device.get_info&lt;Params&gt;())...}; }

标签: c++ c++11 templates c++14 sycl


【解决方案1】:

使用折叠表达式不需要显式循环(或递归)。例如:

#include <iostream>
#include <string>

template <typename T>
void foo(){ std::cout << T{}; }   // just an example

template <typename...Args>
void bar() {
    (foo<Args>(),...);            // call foo for each type in Args
}

int main() {
    bar<int,double,std::string>();
}

要拥有受支持类型的“集合”,您可以使用using collection = std::tuple&lt;int,double,std::string&gt;;

【讨论】:

    【解决方案2】:

    对于所有此类代码,我使用 Boost.Hana 对带有 boost::hana::for_each 的元组进行迭代,无论是从用户的角度来看,还是用于 SYCL 内部实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多