简体   繁体   English

在 C++ 的宏中查找变量的类型

[英]Finding the type of a variable in a macro in C++

Long story short: I need to find the type of a variable to use it in the #if condition macro.长话短说:我需要找到要在#if condition宏中使用的变量类型。 My typeof() in the provided sample is an imagined function, expression, code I would like to know.我在提供的示例中的typeof()是一个想象中的函数、表达式和我想知道的代码。 If even exists...如果甚至存在...
Otherwise, is there any workaround?否则,有什么解决方法吗?

Sample code:示例代码:

template <class T>
class MyClass
{
    T variable;

public:

#if typeof(T) == typeof(int)
    // compile section A
#elif typeof(T) == typeof(string)
    // compile section B
#endif 

};

If you wish to provide some members and/or member functions on some condition, a way is inherit from implement classes via std::conditional_t :如果您希望在某些条件下提供一些成员和/或成员函数,一种方法是通过std::conditional_t从实现类继承:

struct MyClassIntImpl {
    void foo() {}
};
struct MyClassStringImpl {
    void bar() {}
};
struct MyClassDefaultImpl {};

template <class T>
class MyClass : public
    std::conditional_t<std::is_same_v<T, int>, MyClassIntImpl,
    std::conditional_t<std::is_same_v<T, std::string>, MyClassStringImpl,
    MyClassDefaultImpl>>
{
// ...

Where MyClassDefaultImpl is simply the default case, as needed for std::conditional_t .根据std::conditional_t的需要, MyClassDefaultImpl只是默认情况。

Therefore a MyClass<int> object will have the foo() member function:因此MyClass<int>对象将具有foo()成员函数:

int main() {
    MyClass<int> u;
    u.foo();
}

This has some benefits over specialization:这比专业化有一些好处:

  • you don't need to copy & paste the same class for N types您不需要为 N 种类型复制和粘贴相同的类
  • you can do checks like std::is_integral_v , which you can't easily do with specializations.您可以进行像std::is_integral_v这样的检查,这是您无法通过专业化轻松完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM