在 C++ 中如何使用模板调用提供类型的特定成员
How in C++ use templates to call specific members of supplied type
假设我们有两个 类
struct A
{
int x = 1;
};
struct B
{
int y = 2;
};
我想要模板 return 成员的值(在 A 的情况下,我想 return "x" 的值,在 B 的情况下,我想 return "y" 的值)。
调用示例:
const auto myVariable = f<A>();
或
A a;
const auto myVariable = f<A>(a);
我不想有 2 个模板专业化 - 理想情况下,它应该是一个带有某种 "if statement" 的模板,但也许这是不可能的?
它可以用 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;
}
为了使其正常工作,您需要在每个 class 中声明相同的变量或函数名称。
假设我们有两个 类
struct A
{
int x = 1;
};
struct B
{
int y = 2;
};
我想要模板 return 成员的值(在 A 的情况下,我想 return "x" 的值,在 B 的情况下,我想 return "y" 的值)。
调用示例:
const auto myVariable = f<A>();
或
A a;
const auto myVariable = f<A>(a);
我不想有 2 个模板专业化 - 理想情况下,它应该是一个带有某种 "if statement" 的模板,但也许这是不可能的?
它可以用 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;
}
为了使其正常工作,您需要在每个 class 中声明相同的变量或函数名称。