我有一个模板化的类,我在其中定义了引用该模板化类的自由函数.这些自由函数也可以在不同的参数上进行模板化.
从课外我可以调用自由函数.但是,我找不到一个自由函数调用另一个函数的正确语法.
快速举例:
template<typename T> class Foo {
template<typename S>
friend S f(const Foo &) { return S(); }
template<typename S>
friend S g(const Foo &s) {
return f(s); // See below, when instantiated, yields 'no matching function for call to f(const Foo &)'
}
};
float test1() {
Foo<int> o;
return f<float>(o); // Compiles
}
float test2() {
Foo<int> o;
return g<float>(o); // Fails to compile as line above errors
}
Run Code Online (Sandbox Code Playgroud)
(也参见这个链接)
似乎在g()内调用f(s),最外面的模板已经丢失.如何在f调用中重新指定T?我已经检查了GCC4.7,4.8,clang 3.2都有相同的错误.
当您调用时,f(s)您需要指定模板参数,S因为它无法从参数中推断出来s.
但如果你将其更改为f<S>(s)(假设你的意思是用相同的模板参数来调用它S 是g用所谓的),那么你抑制ADL,并在类范围内定义友元函数可以发现的唯一途径是通过ADL.因此,您需要向f全局命名空间添加声明,以便调用g可以找到它.
因此,要使其工作,您需要先添加这些声明 Foo
template<typename T> class Foo;
template<typename S, typename T>
S f(const Foo<T> &);
template<typename S, typename T>
S g(const Foo<T> &);
Run Code Online (Sandbox Code Playgroud)
并将呼叫更改g为f<S>(s)或类似的其他内容f<x>(s)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |