首页 > 解决方案 > 解析在 namespace-d 模板函数中使用的函数

问题描述

在尝试实例化模板函数时,我观察到一些看似奇怪的行为。

简而言之,我正在实现一个模板函数库。出于该库的目的,我假设对于用于实例化这些模板之一的每种类型 T,该库的用户将实现一个具有特定签名的函数,例如:

void foo(const T& t)

我想在封闭的命名空间中定义我的库模板函数,比如 A。同样,我希望这些函数可以在另一个(用户定义的)命名空间中使用,比如 B。我想到的整体使用模式如下:

    #include <string>
    #include <iostream>

    // My library function
    namespace A {

    template <typename T>
    void my_library_function(const T& t) { foo(t); }

    }


    // Intended usage
    namespace B {

    // User writes a function foo(T) for the specific type T they want 
    // to use in conjunction with my_library_function()
    void foo(const std::string&  s) { std::cout << s << std::endl; }

    // User can then use my_library_function() in their own code
    void super_cool_user_function(const std::string& s) { A::my_library_function<std::string>(s); }
    }

    int main()
    {
        std::string s = "Hello world!";
        B::super_cool_user_function(s);
    }

我希望这可以工作,因为在此代码my_library_function()中仅在foo(std::string& s)定义的同一命名空间 B 中使用。但是,在尝试编译时,我收到以下错误:

> In instantiation of ‘void A::my_library_function(const T&) [with T =std::__cxx11::basic_string<char>]’:
>
> example.cpp:8:43: error: ‘foo’ was not declared in this scope
>
> void my_library_function(const T& t) { foo(t); }
>
>example.cpp:8:43: note: suggested alternative:
>
>example.cpp:17:6: note:   ‘B::foo’
>
>void foo(const std::string&  s) { std::cout << s << std::endl; }

所以,我有两个(希望是直截了当的?)问题:

谢谢!

标签: c++templatesnamespacesname-lookup

解决方案


推荐阅读