【发布时间】:2015-07-08 05:41:07
【问题描述】:
考虑一下这个非法代码:
template <int... Is>
struct Object {
void foo() const;
};
template <int... Js>
void Object<0, Js...>::foo() {/*Do whatever*/}
当第一个模板参数为 0 时,我们想特化 foo(),假设第二个参数为 3,第三个 int 为 1,我们也想特化 foo()。所以我找到的解决方案 (不确定它是否是最好的方法)如下:
#include <iostream>
template <int...> struct Foo;
template <int... Is>
struct Object {
int ID; // This member is just to illustrate the case when 'this' is needed in foo().
friend struct Foo<Is...>;
void foo() const {Foo<Is...>::execute(this);} // Pass 'this' in case it is needed.
};
template <int... Is>
struct Foo<0, Is...> {
static void execute (const Object<0, Is...>* object) {std::cout << "First int = 0, ID = " << object->ID << ".\n";}
};
template <int N, int... Is>
struct Foo<N, 3, Is...> {
static void execute (const Object<N, 3, Is...>* object) {std::cout << "Second int = 3, ID = " << object->ID << ".\n";}
};
template <int M, int N, int... Is>
struct Foo<M, N, 1, Is...> {
static void execute (const Object<M, N, 1, Is...>* object) {std::cout << "Third int = 1, ID = " << object->ID << ".\n";}
};
int main() {
Object<0,5,8,2>{4}.foo();
Object<4,3,2,5,3>{2}.foo();
Object<4,2,1>{0}.foo();
}
首先,这个解决方案好用吗?接下来,如果我们尝试Object<0,3,1,4>{8}.foo();,就会出现问题,因为规范不完整。因此,假设最早匹配的专用 int 将始终优先。所以在这种情况下,Object<0,3,1,4>{8}.foo(); 应该因为 0 而运行第一个特化,而 Object<9,3,1,4>{8}.foo(); 因为 3 应该运行第二个特化,依此类推。如何执行该规则?
【问题讨论】:
标签: c++ templates c++11 specialization