c++ - 解析在 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; }
所以,我有两个(希望是直截了当的?)问题:
为什么会出现这个错误?
是否有一种简洁的方法来修改我的方法(模板的实现)以启用上面显示的预期用途?
谢谢!
解决方案
推荐阅读
- javascript - 看起来我的 javascript 中断了我的 css
- angular - router.navigate 中的 {skipLocationChange : true} 不起作用;改变状态
- c# - 没有 APIController 属性的版本化 API Explorer
- javascript - 如何从 ES6 JavaScript 类实例中获取源代码位置?
- java - Javafx Google 按高度和经度映射标记
- c - 我们可以减去 NULL 指针吗?
- javascript - Angular6:无法访问获取异步数据的模板中的 js 变量
- java - 在 Netbeans Java 应用程序上,如何通过单击按钮打开新页面(不是弹出窗口)?
- typescript - 如何声明打字稿模块以防止“隐式具有'任何'类型”错误?
- python - 当 DEBUG=False 时不会触发自定义记录器