簡體   English   中英

是否可以通過模板類型更改靜態const類成員的值?

[英]Is it possible to change the value of a static const class member by template type?

我真的不知道這方面的術語,我只舉一個例子:

template <typename T>
struct value_holder {
    T value;
    static const bool is_integer = ??; // if T is int or long set this to true, else set false
}

這樣我做的時候

value_holder<float> floaty;
std::cout << floaty.is_integer << "\n";

它會打印0

我必須如何定義成員is_integer才能做到這一點?

您可以使用std::is_same做到這一點。
它遵循一個最小的有效示例:

#include<type_traits>

template <typename T>
struct value_holder {
    T value;
    static const bool is_integer = std::is_same<int, T>::value or std::is_same<long, T>::value;
};

int main() {
    static_assert(value_holder<int>::is_integer, "!");
    static_assert(not value_holder<char>::is_integer, "!");
}

另一種可能的方法是基於模板專門化。 這種方式應該可以起作用:

template <typename T>
struct value_holder {
    T value;
    static const bool is_integer = false;
};

template <>
struct value_holder<int> {
    int value;
    static const bool is_integer = true;
};

template <>
struct value_holder<long> {
    long value;
    static const bool is_integer = true;
};

無論如何,從我的角度來看,這有點冗長,如果您的類包含多個數據成員,可能會很煩人。

正如昆汀的回答所說,您使用類型特征。 std::is_integral在您的示例中很有意義:

template <typename T>
struct value_holder {
    T value;
    static constexpr bool is_integer = std::is_integral<T>::value;
};

但這與您的評論不完全一致。 如果您確實希望is_integer僅在intlong為true,則可以定義一個自定義類型特征:

template <typename T>
struct is_int_or_long : std::false_type {};

template <>
struct is_int_or_long<int> : std::true_type {};

template <>
struct is_int_or_long<long> : std::true_type {};

template <typename T>
struct value_holder {
    T value;
    static constexpr bool is_integer = is_int_or_long<T>::value;
};

當然,可以通過使用std::is_same特性來縮短該std::is_same

template <typename T>
struct value_holder {
    T value;
    static constexpr bool is_integer = std::is_same<T, int>::value || std::is_same<T, long>::value;
};

您正在尋找類型特征 您可能會對std::is_integral感興趣。

暫無
暫無

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

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