我想獲取具有特定模板引數(鍵)的父級的型別名。
例如,如果我有一個 parent MyParent<int, 1>,我希望能夠MyParent<int, 1>只用“1”從我的孩子那里得到那個 type()。如果我有,MyParent<float,2>我希望能夠MyParent<float, 2>只用'2'來獲得那種型別()。
基本上,我想從“鍵”(1、2、3 等)中獲取型別名(MyParent<float, 1>, MyParent<int, 2> 等)
我在 C 20 模式下使用 MSVC 編譯器。
這是可以做到這一點的作業代碼(但它有一個缺點):
#include <iostream>
template<std::size_t key>
class KeyClass {};
template<class Type, std::size_t key>
class parent
{
using keyclass = KeyClass<key>;
using self = parent<Type, key>;
public:
template<std::same_as<keyclass> T>
static self GetType() {}
};
class test :
public parent<int, 1>,
public parent<float, 2>
{
public:
using parent<int, 1>::GetType;
using parent<float, 2>::GetType;
};
int main()
{
std::cout << typeid(decltype(test::GetType<KeyClass<1>>())).name() << std::endl;
std::cout << typeid(decltype(test::GetType<KeyClass<2>>())).name() << std::endl;
}
這將按預期列印:“class parent<int,1> class parent<float,2>”。我可以自由地使用這些型別,獲取它們的靜態成員并用它們做其他事情,這正是我想要的。
The downside is that I have to explicitly specify that I'm using the GetType method from every one of my parents. Which is quite lame, since I have to type everything twice (inheriting once, then specifying 'using'). Imagine having tens of keys ...
Are there any other ways to do this without repeating my code? For example, is there any way to specify 'using GetType` for all the parents in one line somehow? Or to make them automatically inherited or something, so that I don't have to specify 'using' at all?
Or maybe there's a different way to do what I want (to get a type at compile-time from some key (a template parameter), for example 1 should return Myparent<int, 1>, 2 should return MyParent<int, 2>)?
I don't want to use the preprocessor for this.
uj5u.com熱心網友回復:
為了避免using為每個父類的成員撰寫宣告,您可以撰寫一個可變引數類模板包裝器,為所有型別公開該成員(如此處所示的 Overloader模式)
template<typename... Ts>
struct Bases : Ts...
{
using Ts::GetType...;
};
現在你的test類可以從這個包裝器繼承為
class test : public Bases<parent<int, 1>,
parent<float, 2>>
{};
這是一個演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447265.html
上一篇:要求模板變數無效的語法是什么?
