目标是在类的模板参数是特定的模板化类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
?我知道可以通过专门化来实现,但是这需要大量的代码重构,因此我希望不必这样做。
答案 0 :(得分: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>();