簡體   English   中英

在 C++ 的宏中查找變量的類型

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

長話短說:我需要找到要在#if condition宏中使用的變量類型。 我在提供的示例中的typeof()是一個想象中的函數、表達式和我想知道的代碼。 如果甚至存在...
否則,有什么解決方法嗎?

示例代碼:

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 

};

如果您希望在某些條件下提供一些成員和/或成員函數,一種方法是通過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>>
{
// ...

根據std::conditional_t的需要, MyClassDefaultImpl只是默認情況。

因此MyClass<int>對象將具有foo()成員函數:

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

這比專業化有一些好處:

  • 您不需要為 N 種類型復制和粘貼相同的類
  • 您可以進行像std::is_integral_v這樣的檢查,這是您無法通過專業化輕松完成的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM