【问题标题】:Using concepts to enable member functions when the template parameter is a specific templated class当模板参数是特定模板类时,使用概念启用成员函数
【发布时间】:2020-04-17 21:41:32
【问题描述】:

目的是在类的模板参数是特定模板类Ptr <U>时启用成员函数。以下代码确实有效,但需要重复模板参数U

#include <iostream>
using namespace std;

template <class T> class Ptr
{
public:
};

template <typename T, typename U> concept is_a_Ptr = std::is_same <T, Ptr <U>>::value == true;

template <class T> class Container
{
public:
  void PlainFoo () {};
  template <class U> void OptionalFoo () requires is_a_Ptr <T,U> {};
};

int main(int argc, char* argv[])
{
  Container <Ptr <int>> foo;
  foo.OptionalFoo <int> (); // Requires <int> to be specified
  // foo.OptionalFoo (); // Would like to be able to do this
  return 0;
}

有没有办法避免指定 int ?我知道它可以通过专业化来实现,但这需要大量的代码重构,所以我希望不必这样做。

【问题讨论】:

  • 你真的不应该这样做。 Ptr 提供的任何属性都可能由其他类型提供。实际上,概念的全部意义在于检查感兴趣的属性本身,而不是特定的类类型或模板实例化。
  • 点了,事实上我需要它来申请其他课程。实际上(并简化了一点)我有一组类 Ptr1、Ptr2、...,它们都可以从 Ptr_Base 派生。那是下一步。我不想在没有先找到一个更简单的例子的情况下走这条路。

标签: c++ c++20 c++-concepts


【解决方案1】:

有没有办法避免指定int

我建议在 Ptr 中添加一个类型别名,如下所示:

template <class T> class Ptr
{
public:
    using type = T;
};

然后你可以默认OptionalFoo()的类型参数:

template <class U = typename T::type> 
void OptionalFoo () requires is_a_Ptr <T,U> {};

这样您就不必再次指定类型,您可以将其称为:

Container <Ptr <int>> foo;
foo.OptionalFoo (); // identical to foo.OptionalFoo<int>();

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2020-05-14
    • 2022-01-10
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多