【问题标题】:How to use user-defined deduction guides for multiple template parameters? [duplicate]多个模板参数如何使用自定义推导指南? [复制]
【发布时间】:2018-07-18 09:41:55
【问题描述】:

我可以为具有多个模板参数的类使用用户定义的推导指南吗?我希望从构造函数参数中推导出一个指定的模板参数。构造类时,必须在<>-括号中指定所有其他模板参数。示例:

#include <iostream>

template<typename T, typename A>
struct Hello
{
    Hello(T x) : x(x) {}
    T x;
    A y;
};

Hello<A>(int) -> Hello<int, A>; // This is not a valid syntax but shows what i want to do 

int main()
{    
    Hello h = Hello<float>((int)1); // this should be deduced to Hello<int, float>
    std::cout << h.x << std::endl;
    return 0;
}

【问题讨论】:

  • 恕我直言,这个解决方案在提供的情况下不起作用:有两个模板参数,只有一个在构造函数中;用户在其问题中没有提到 C++-17,所以它可能不可用。请撤销重复标记。

标签: c++ templates template-argument-deduction


【解决方案1】:

我可以考虑三种方法。

template <typename T, typename A>
struct Hello {
  Hello(T x) : x(x) {}
  T x;
  A y;
};

// Approach 1: use type aliases
// Requires at least c++-11

template <typename A>
using HelloInt = Hello<int, A>;

// Approach 2: use function factories

template <typename A>
Hello<int, A> make_hello_int(int i) {
    return Hello<int, A>(i);
}

// Approach 3: use template partial deduction

template <typename A, typename T>
Hello<T, A> make_hello(T i) {
  return Hello<T, A>(i);
}

int main() {
  // `auto` requires at least c++-11
  auto k = HelloInt<float>(1);
  std::cout << k.x << std::endl;
  std::cout << make_hello_int<float>(2).x << std::endl;
  std::cout << make_hello<float>(3).x << std::endl;
  return 0;
}

【讨论】:

    【解决方案2】:

    在 C++11 中,您的模板参数不能从构造函数调用中推断出来。在 C++17 中它可以,但对您的情况没有太大帮助,因为只允许完整的模板特化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      相关资源
      最近更新 更多