简体   繁体   中英

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. My typeof() in the provided sample is an imagined function, expression, code I would like to know. 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 :

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 .

Therefore a MyClass<int> object will have the foo() member function:

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
  • you can do checks like std::is_integral_v , which you can't easily do with specializations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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