ein*_*ica 5 c++ templates overloading partial-specialization template-specialization
我想写下面的内容:
template <typename S, typename T> void foo() {
/* code for the general case */
}
template <typename T> void foo<MySType,T>() {
/* partially specialized code - for any kind of T, but when S is MySType */
}
Run Code Online (Sandbox Code Playgroud)
或者,在其他情况下,以下内容:
template <typename S, typename T> void bar(const S& a, const T& b) {
/* code for the general case */
}
template <typename T> void bar<MySType,T>(const MySType& a, const T& b) {
/* partially specialized code - for any kind of T, but when S is MySType */
}
Run Code Online (Sandbox Code Playgroud)
C++(11)不允许我这样做.
现在,我读到了这个问题及其答案 ; 让我们假设我购买了为什么我们没有部分模板专业化的解释(或者只是假设我生活在现实中并且实际上想要编写代码).那么,我该怎么做呢?
我真的不想将这些函数包装在一个类中,除非这绝对是我的最后手段.
超载!在各种专业化方面,重载都是优越的.过载分辨率的一部分是选择最专业的过载.只需将"specializations"声明为重载,如果部分特化将具有,它将起作用.
但是,避免使用显式模板参数.您可以改用标签调度.
template< typename t >
struct tag {};
template <typename S, typename T> foo( tag<S>, tag<T> ) {
/* code for the general case */
}
template <typename T> foo( tag<MyType>, tag<T> ) {
/* partially specialized code - for any kind of T, but when S is MyType */
}
Run Code Online (Sandbox Code Playgroud)
由于标记是空的并且通过值传递,因此编译器可以消除它们对函数调用开销的贡献.
另一种选择是使用辅助类模板,您可以在其中进行部分专业化,并使用不需要部分专业化本身的包装函数隐藏它:
#include <iostream>
template<typename S, typename T>
struct foo_helper {
void foo() {
std::cout << "general func" << std::endl;
}
};
struct MyType {};
template <typename T>
struct foo_helper <MyType,T> {
void foo() {
std::cout << "partially specialized code - for any kind of T, but when S is MyType" << std::endl;
}
};
template<typename S, typename T>
void foo() {
foo_helper<S, T>().foo();
}
int main () {
foo<int, int>();
foo<int, double>();
foo<MyType, long>();
}
Run Code Online (Sandbox Code Playgroud)
这也是有效的 C++98/03。
归档时间: |
|
查看次数: |
174 次 |
最近记录: |