我有以下代码
template <typename T>
auto CallMe(int param) -> void {
...
}
auto Test(int userInput) -> void {
int paramToUse = SomeFunction(userInput);
if (userInput == 0) {
CallMe<__int32>(paramToUse);
} else if (userInput == 1) {
CallMe<__int16>(paramToUse);
} else if (userInput == 2) {
CallMe<__int8>(paramToUse);
} else if (userInput == 3) {
...
}
我的问题是,由于CallMe()
除了template type之外,所有对to的调用都完全相同T
,因此在C ++中是否有一种方法可以将类型分配给每个条件分支中的变量,并将其传递到CallMe()
一个位置,例如
typename T;
if (userInput == 0) {
T = __int32;
} else if (userInput == 1) {
T = __int16;
} else if (userInput == 2) {
T = __int8;
} else if (userInput == 3) {
...
CallMe<T>(paramToUse);
这样,如果CallMe
更改了的签名,则只需更新一行。
怎么样:
decltype(CallMe<__int32>)* callable; // function pointer
// set the function address as necessary
if (userInput == 0) {
callable = CallMe<__int32>;
} else if (userInput == 1) {
callable = CallMe<__int16>;
} else if (userInput == 2) {
callable = CallMe<__int8>;
} else {
// ...
}
callable(paramToUse); // call it
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句