通过参数字符串化宏调用模板函数

Calling a template function through a parameter-stringifying macro?

本文关键字:调用 函数 参数 字符串      更新时间:2023-10-16

我正在编写一个帮助程序函数,它应该使我的一些(C/C++新手(同事从参数存储中检索命名的标量参数值更简单、更万无一失。

问题是,参数存储只能存储 double 类型的值,但是将调用此函数的代码是一大堆被转换为 C++ 的 C,因此在某些地方可能会导致问题(或至少是虚假警告(只是在预期intlong的地方转储double

所以我想到了使帮助程序函数成为模板函数的想法,返回类型是一个未指定的模板参数 - 这样,调用者必须手动指定返回类型应该是什么。

但是,该函数的参数是一个 unicode 字符串 ( const wchar_t* (,我希望用户能够像以前使用符号名称一样调用它(以前使用宏完成(。

我不知道如何将模板函数的东西与自动字符串化参数的方法结合起来!任何人都可以提供一些指导吗?出于美学原因,我基本上正在寻找一个聪明的宏/模板黑客;-(

作为宏:

// the return type is always double
#define GetParameter(parameterName) GetParameterFromParameterStore(L#parameterName)

作为模板函数:

// the user has to remember to pass the argument as a (wide) string
template<class T> T GetParameter(const wchar_t* parameterName)
{
    return (T)GetParameterFromParameterStore(parameterName);
}

编辑:理想情况下,我希望能够调用这样的函数:

int _volumePct = GetParameter<int>(VolumeInPercent);

(没有任何额外的装饰或语法(。

一种方法是创建一个新的宏来字符串化

#define Stringify(parameter) L#parameter

并将其传递给 GetParameter 模板函数,如下所示:

GetParameter<int>(Stringify(hello there));

这是您要做的吗? 但是,我觉得最好使用现有宏对结果进行类型转换。