【问题标题】:Overload function template using a templated type使用模板化类型重载函数模板
【发布时间】:2021-03-29 21:35:28
【问题描述】:

我有一个这样的函数:

template <typename T, typename F>
T function(const F& f) const;

这个函数有各种重载,其中一些是基于概念的。类似于以下内容:

template <typename T, std::integral F>
T function(const F& f) const;

template <typename T, std::same_as<double> F>
T function(const double& f) const;

现在我想使用模板类型添加重载,类似于以下内容:

template <typename T, std::same_as<std::vector<V>> F>
T function(const std::vector<V>& f) const;

为此,我需要指定V 类型。但我找不到允许在不破坏代码的情况下指定 V 的语法。

函数调用如下:

T result = function<T, F>(f);

这意味着,模板类型是明确提供的,重载可能不会改变模板参数的数量或顺序,否则编译器会报错。

如何解决?

【问题讨论】:

  • 但是,确切地说,你想对V指定什么?
  • @max66 V 使用前只需要了解即可。

标签: c++ overloading c++20 function-templates function-templates-overloading


【解决方案1】:

我目前无法使用编译器来测试它,但这应该足够了:

template <typename T, typename V>
T function(const std::vector<V>& f) const;

【讨论】:

  • 我在评论中提出了这个建议,但我不确定这是 OP 所追求的。
  • @einpoklum 根据 OP 对另一个答案的评论,我相信你是对的。哦,好吧,我回答了实际提出的问题......
  • 刚刚改变了你提出的问题。考虑删除您的答案,因为它不再回答问题了吗?
【解决方案2】:

您必须编写自己的概念。

通过检查一个类是否是来自Check if class is a template specialization? 的特化,并添加了一个要求子句以仅接受标准分配器。

template <class T, template <class...> class TT>
struct is_specialization : std::false_type {};

template <template <class...> class TT, class... Ts>
struct is_specialization<TT<Ts...>, TT> : std::true_type {};

template <class T, template <class...> class TT>
concept specializes = is_specialization<T, TT>::value;

template <typename T, specializes<std::vector> F>
T function(const F& f) const requires specializes<F::allocator_type, std::allocator>;

除非可以手动提供模板参数,否则重载解析应该与以下重载一起使用:

template <typename T, class V>
T function(const std::vector<V>& f) const;

【讨论】:

    【解决方案3】:

    也许使用 requires-clause

    template <typename T, typename F>
      requires std::same_as<std::vector<typename F::value_type>, F>
    T function(const F& f) const;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多