当模板参数为特定模板时使用概念启用成员函数class

Using concepts to enable member functions when the template parameter is a specific templated class

目的是在class的模板参数是特定模板classPtr <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 ?我知道它可以通过专业化来实现,但这需要大量的代码重构,所以我希望不必那样做。

Is there a way to avoid having to specify the 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>();