[英]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();
}
這比專業化有一些好處:
std::is_integral_v
這樣的檢查,這是您無法通過專業化輕松完成的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.