[英]How in C++ use templates to call specific members of supplied type
假設我們有兩個類
struct A
{
int x = 1;
};
struct B
{
int y = 2;
};
我想要一個模板,該模板將返回成員的值(在AI的情況下,其返回值是“ x”,在BI的情況下,其返回值是“ y”)。
示例調用:
const auto myVariable = f<A>();
要么
A a;
const auto myVariable = f<A>(a);
我不想擁有2個模板專長-理想情況下,它將是一個帶有某種“ if語句”的模板,但也許不可能嗎?
可以用C ++ 11(但不能用C ++ 14)編寫。
通常,遇到此類問題時如何使用模板-很大的模板,並且只需要在一個或兩個位置取不同成員的值-可以根據該變量的類型推論得出。
問題:不必要,不允許修改A類和B類
為什么要完全使用模板?
int f(const A& a) { return a.x; }
int f(const B& b) { return b.y; }
萬一您因為在編譯時想要在A和B之間切換而要求模板,並且您有理由不直接鍵入A或B的定義...
struct A
{
int x;
};
struct B
{
int y;
};
struct A1 : public A { int Get() const { return x; } };
struct B1 : public B { int Get() const { return y; } };
// Begin possible shortcut avoiding the template below:
#ifdef USE_A
typedef A1 Bar;
#endif
#ifdef USE_B
typedef B1 Bar;
#endif
// End possible shortcut.
template <class _Base>
struct CompileTimeAOrB
: public _Base
{
int Get() const
{
return _Base::Get();
}
};
#define USE_A
//#define USE_B
#ifdef USE_A
typedef CompileTimeAOrB<A1> Foo;
#endif
#ifdef USE_B
typedef CompileTimeAOrB<B1> Foo;
#endif
編輯 :由於不能更改A和B,引入A1,B1;)
#include <iostream>
struct A
{
int value;
A() : value(2) {}
};
struct B
{
int value;
B() : value(4) {}
};
template <typename T>
int GetValue(T t)
{
return t.value;
}
int main()
{
A a;
B b;
std::cout << GetValue(a) << std::endl;
std::cout << GetValue(b) << std::endl;
return 0;
}
為了使其工作,您需要在每個要使用的類中聲明相同的變量或函數名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.