0

如何在模板实例化时找到模板参数的类型?例如,我希望将以下模板实例化为 2 个不同的函数,具体取决于参数:

template <typename T> void test(T a) {
    if-T-is-int {
        doSomethingWithInt(a);
    } else {
        doSomethingElse(a);
    }
}

当用 实例化时int,结果函数将是:

void test(int a) { doSomethingWithInt(a); }

当用例如实例化时float,它将是:

void test(float a) { doSomethingElse(a); }
4

2 回答 2

1
template <typename T> void test(T a) {
    doSomethingElse(a);
}

template <> void test(int a) {
    doSomethingWithInt(a);
}

应该可以,但是您需要考虑获得int &,const int等的情况。

于 2012-08-15T01:38:58.913 回答
1

在您的情况下,听起来您只需要两个重载版本intfloat。描述的其他类型没有行为,因此不需要模板。

void test (int i) {
    doSomethingWithInt(i);
}

void test (float f) {
    doSomethingElse(f);
}

如果您确实需要其他类型的案例,请添加一个普通的模板版本。特定的重载优先。例如,请参见此处

于 2012-08-15T01:50:12.803 回答