[英]Is it possible in C/C++ to put the name of a function into the code at compile time?
[英]C++: disambiguate this code at compile time?
我試圖找到一種方法來消除這個代碼的歧義(在編譯時)(因為兩天: - ) - > 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;
}
這是一個有效的運行時解決方案
#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;
}
有解決方案嗎?
注意:我發現的一種可能方式是std :: is_base_of <>,但這是非常有限的(模板實例化深度)
這是一個模糊的名稱查找,在多重繼承的情況下,會在查找中隱藏名稱。 它甚至沒有檢查使用哪個過載。
您可以通過在struct A
的定義中添加以下內容來解決此問題:
using BASE<X,1>::get_value;
using BASE<Y,0>::get_value;
這兩個語句將兩個基類的名稱get_value
添加到A中,因此編譯器可以繼續使用其沉悶的生命並將其作為重載進行檢查。
基於Atash的答案:假設您不想在基數列表和使用聲明中重新鍵入基類列表,您可以使用如下的間接:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.