首页 > 解决方案 > 显示名称函数模板名称

问题描述

我有一个正在尝试处理的函数包装类。

我希望能够显示传递给模板的函数的名称。

template<auto Func>
struct FuncWrapper final {
    FuncWrapper() {
        StrFuncName = typeid(Func).name();
        std::cout << StrFuncName << std::endl;
    }

    template<typename... Args>
    auto operator()(Args&&... args) const { }

    std::string StrFuncName;
};

void Function() { }

FuncWrapper<Function> wrapper;

标签: c++c++17

解决方案


这在标准 C++ 中是不可能的。拆解 typeid 也无济于事,因为您只会获得函数类型的名称,而不是您实际赋予函数的名称。

您可以获得的最接近的是预定义__func__常量,但它只存在于您想要获取名称的函数范围内。

void foo()
{
    std::cout << __func__; // will print "foo"
}

推荐阅读