专门处理一个参数(C++模板)的两个模板参数

Specializing with two template arguments for an argument (C++ template)

本文关键字:参数 两个 模板 一个 处理 C++      更新时间:2023-10-16

我不知道如何正确描述这个问题,但基本上我想知道的是,这样的东西可以毫无问题地编译:

// prototype
template <class T>
void pretty_function(T arg);
// specialization
template <class U, class V>
void pretty_function<U<V>>(T arg);

所以我想用类型U<V>,其中类型U需要模板参数V。我想我可以在本地工作站上轻松地测试它,但我只是把它留在这里供将来参考。

听起来您想要声明pretty_function的专门化,它只接受形式为U<V>的类型,其中U可以是任何类模板,V可以是任何类型。这将是部分专门化,因为没有完全指定模板参数T。C++不支持函数模板的部分专用化。通常的解决方法是将其发送到一个可以部分专用的助手类模板:

namespace detail {
template <class T>
struct pretty_function_helper {
static void doit(T arg) { /* implementation */ }
};
// partial specialization
template <template <class> class U, class V>
struct pretty_function_helper<U<V>> {
static void doit(U<V> arg) { /* implementation */ }
};
}
template <class T> void pretty_function(T arg) {
detail::pretty_function_helper<T>::doit(arg);
}