You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建指向已知返回类型模板函数的函数指针

解决带约束模板函数的函数指针创建问题

模板函数本身并非可直接寻址的具体函数,必须先实例化为特定类型的具体函数后,才能获取其地址。你的m_print模板带有std::convertible_to<T, std::wstring>约束,因此必须选择符合该约束的类型(如std::wstring、const wchar_t*等)来实例化模板,再创建函数指针。

具体实现方式

  1. 显式指定模板参数实例化
    直接指定符合约束的T类型,获取对应实例化函数的地址:

    #include <string>
    #include <iostream>
    
    template <typename T>
    void m_print(const T& message) requires std::convertible_to<T, std::wstring>
    {
        std::wcout << message << std::endl;
    }
    
    int main() {
        // 实例化T为std::wstring的版本
        void (*fp_wstring)(const std::wstring&) = &m_print<std::wstring>;
        fp_wstring(L"Hello, std::wstring");
    
        // 实例化T为const wchar_t*的版本(该类型可转换为std::wstring)
        void (*fp_cwchar)(const wchar_t* const&) = &m_print<const wchar_t*>;
        fp_cwchar(L"Hello, const wchar_t*");
    
        return 0;
    }
    
  2. 使用auto简化指针类型推导
    如果你不想手动写复杂的指针类型,可以用auto让编译器自动推导实例化后的函数指针类型:

    auto fp = &m_print<std::wstring>;
    fp(L"Hello with auto");
    
  3. 使用std::function封装(可选)
    若需要更灵活的函数对象封装,可结合std::function:

    #include <functional>
    
    std::function<void(const std::wstring&)> func = m_print<std::wstring>;
    func(L"Hello with std::function");
    

关键注意点

  • 必须选择满足std::convertible_to<T, std::wstring>约束的类型来实例化模板,否则编译器会因违反约束报错(比如尝试m_print<int>会直接编译失败)。
  • 当T为指针类型(如const wchar_t*)时,函数参数是const T&,即const wchar_t* const&(对指针的const引用),函数指针的类型需要与之匹配(不过部分编译器会允许隐式兼容,但显式写出更严谨)。

内容的提问来源于stack exchange,提问作者BahiGoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:23:19