使用并重载基类的模板成员函数? [英] using and overloading a template member function of a base class?
问题描述
以下,结构Y
重载了X
的成员函数f
.这两个重载都是模板函数,但是采用不同的参数(typename
和int
)进行明确指定:
In the following, struct Y
overloads X
's member function f
. Both overloads are template functions, but take different arguments (typename
and int
), to be explicitly specified:
struct X
{
template <typename> static bool f() { return true; }
};
struct Y : public X
{
using X::f;
template <int> static bool f() { return false; }
};
int main()
{
std::cout << Y::f <void>() << " " << Y::f <0>() << std::endl;
}
这将按预期使用gcc打印1 0
.但是,clang(3.3)抱怨
This prints 1 0
using gcc, as expected. However, clang (3.3) complains that
[...] error: no matching function for call to 'f'
std::cout << Y::f <void>() << " " << Y::f <0>() << std::endl;
^~~~~~~~~~~
[...] note: candidate template ignored: invalid explicitly-specified argument
for 1st template parameter
template <int> static bool f() { return false; }
^
即只能看到Y
的版本.我已经尝试过
i.e., can only see Y
's version. I've tried
using X::template f;
相反,没有成功.非静态(模板)成员函数也会发生同样的情况.那是一个错误吗?
instead, with no success. The same happens for non-static (template) member functions. So is this a bug?
推荐答案
这个难题最近是根据另一个答案向我解释的.
This conundrum was recently explained to me in the light of another answer.
在#clang IRC频道中:
From the #clang IRC channel:
[01:16:23] <zygoloid> Xeo: this is a weird corner of the language where clang conforms but the rule is silly
[01:16:31] <Xeo> ... really? :(
[01:16:45] <zygoloid> Xeo: when deciding whether a using-declaration is hidden, we're not allowed to look at the template-parameter-list (nor the return type, iirc)
[01:17:04] <zygoloid> so the derived class declaration of operator()(T) suppresses the using-declaration
[01:17:19] <Xeo> because it has the same signature / parameter types?
[01:17:40] <zygoloid> rigth
解决方法是不在uses
派生版本的类中定义f
.而是将其移到辅助帮助程序类中(在这种情况下,这是一个问题,您认为应该赢得哪个定义).
The workaround is to not define f
in the class that uses
the derived version. Instead, move it into an auxiliary helper class (which, in this case begs the question, which definition you reckon should win).
-
请参阅此处了解我之前遇到的问题: Lambda函数作为基础类
以及如何使用额外的基类对其进行修复:
And here how to fix it using an extra base-class:
@Xeo还是修复了它,由于某种原因,这种形式不适合clang ++ stackoverflow.com/a/18432618/85371
信用:感谢@Xeo和休息室中的人员挖掘出这个愚蠢的规则"
Credits Thanks to @Xeo and people in the Lounge for unearthing this "silly rule"
这篇关于使用并重载基类的模板成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!