C++ C++;:在编译时消除这段代码的歧义?
我试图找到一种消除代码歧义的方法(在编译时)(因为两天:-)->get_值很模糊C++ C++;:在编译时消除这段代码的歧义?,c++,templates,ambiguous,C++,Templates,Ambiguous,我试图找到一种消除代码歧义的方法(在编译时)(因为两天:-)->get_值很模糊 #include <iostream> template <typename T> struct type2type {}; template<class T, int val> struct BASE { static constexpr int get_value ( type2type< T > ) { return val; } };
#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;
}
#包括
模板
结构类型2类型{};
模板
结构基
{
静态constexpr int get_值(type2type)
{
返回val;
}
};
类X{};
类Y{};
结构A:
公共基地,
公共基础
{};
int main(int argc,字符**argv)
{
A{};
std::cout{}{});
}
私人:
虚拟整数从基(type2type)常量中获取值=0;
};
模板
类库:
公共虚拟
{
虚拟整数从基(type2type)常量覆盖中获取值
{
返回val;
}
};
类X{};
类Y{};
结构A:
公共基地,
公共基础
{};
int main(int argc,字符**argv)
{
A{};
std::cout::get_value()这是一个不明确的名称查找,在多重继承的情况下,它会在查找中隐藏名称。它甚至无法检查要使用哪个重载
您可以通过在结构A的定义中添加以下内容来解决此问题:
using BASE<X,1>::get_value;
using BASE<Y,0>::get_value;
使用BASE::get_值;
使用BASE::get_值;
这两条语句将两个基类中的名称get\u value
添加到A中,因此编译器可以继续其单调的生活,并将它们作为重载进行检查。基于Atash的答案:假设您不想在基列表和using声明中重新键入基类列表,则可以使用间接寻址像这样:
#include <iostream>
template <typename T>
struct type2type {};
template<class T, int val>
struct BASE
{
static constexpr int get_value ( type2type< T > const& )
{
return val;
}
};
class X {};
class Y {};
template <typename...> struct AUX;
template <typename Base, typename... Bases>
struct AUX<Base, Bases...>: Base, AUX<Bases...> {
using Base::get_value;
using AUX<Bases...>::get_value;
};
template <typename Base>
struct AUX<Base>: Base {
using Base::get_value;
};
struct A :
public AUX<BASE< X, 1 >, BASE< Y, 0 > >
{
};
int main ()
{
A a {};
std::cout << a.get_value ( type2type< X >() ) << std::endl;
}
#包括
模板
结构类型2类型{};
模板
结构基
{
静态constexpr int get_值(type2typeconst&)
{
返回val;
}
};
类X{};
类Y{};
模板结构辅助;
模板
结构辅助:基础,辅助{
使用Base::get_值;
使用AUX::get_值;
};
模板
结构辅助:基本{
使用Base::get_值;
};
结构A:
公共辅助,基本>
{
};
int main()
{
A{};
STD::CUT())你调用一个A类型的对象的GETYOUE值,它里面有两个基本对象。哪个编译器应该选择?+ 1。这是我曾经在C++中对MIXIN的一个很好的仿真(但现在我使用D*<)@monotomy您可以将该样板文件移动到一个中间类,该类以线性方式从各种BASE
类型继承,然后使用Tail::get_value
和使用Head::get_value
执行操作。
#include <iostream>
template <typename T>
struct type2type {};
template<class T, int val>
struct BASE
{
static constexpr int get_value ( type2type< T > const& )
{
return val;
}
};
class X {};
class Y {};
template <typename...> struct AUX;
template <typename Base, typename... Bases>
struct AUX<Base, Bases...>: Base, AUX<Bases...> {
using Base::get_value;
using AUX<Bases...>::get_value;
};
template <typename Base>
struct AUX<Base>: Base {
using Base::get_value;
};
struct A :
public AUX<BASE< X, 1 >, BASE< Y, 0 > >
{
};
int main ()
{
A a {};
std::cout << a.get_value ( type2type< X >() ) << std::endl;
}