Mon*_*omy 6 c++ templates ambiguous
我试图找到一种方法来消除这个代码的歧义(在编译时)(因为两天: - ) - > get_value是ambugiuous.
#include <iostream>
template <typename T>
struct type2type {};
template<class T, int val>
struct BASE
{
static constexpr int get_value ( type2type< T > )
{
return val;
}
};
class X {};
class Y {};
struct A :
public BASE< X, 1 >,
public BASE< Y, 0 >
{};
int main ( int argc, char **argv )
{
A a {};
std::cout << a.get_value ( type2type< X >{} ) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这是一个有效的运行时解决方案
#include <iostream>
template <typename T>
struct type2type {};
template<class T>
struct VIRTUAL
{
int get_value () const
{
return get_value_from_BASE ( type2type< T > {} );
}
private:
virtual int get_value_from_BASE ( type2type< T > ) const = 0;
};
template<class T, int val>
class BASE :
public VIRTUAL< T >
{
virtual int get_value_from_BASE ( type2type< T > ) const override
{
return val;
}
};
class X {};
class Y {};
struct A :
public BASE< X, 1 >,
public BASE< Y, 0 >
{};
int main ( int argc, char **argv )
{
A a {};
std::cout << a.::VIRTUAL< X >::get_value () << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
有解决方案吗?
注意:我发现的一种可能方式是std :: is_base_of <>,但这是非常有限的(模板实例化深度)
这是一个模糊的名称查找,在多重继承的情况下,会在查找中隐藏名称.它甚至没有检查使用哪个过载.
您可以通过在struct A定义中添加以下内容来解决此问题:
using BASE<X,1>::get_value;
using BASE<Y,0>::get_value;
Run Code Online (Sandbox Code Playgroud)
这两个语句将get_value两个基类的名称添加到A中,因此编译器可以继续使用其沉闷的生命并将其作为重载进行检查.