简体   繁体   English

是否可以通过模板类型更改静态const类成员的值?

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

I don't really know the terminology on this, I'll just do an example: 我真的不知道这方面的术语,我只举一个例子:

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
}

so that when I do 这样我做的时候

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

it would print 0 它会打印0

How would I have to define the member is_integer so it would do that? 我必须如何定义成员is_integer才能做到这一点?

You can use std::is_same to do that. 您可以使用std::is_same做到这一点。
It follows a minimal, working example: 它遵循一个最小的有效示例:

#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, "!");
}

Another possible approach is based on template specialization. 另一种可能的方法是基于模板专门化。 Something along this way should work: 这种方式应该可以起作用:

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;
};

Anyway it's a bit more verbose from my point of view and can be annoying if your class contains more than a couple data members. 无论如何,从我的角度来看,这有点冗长,如果您的类包含多个数据成员,可能会很烦人。

As Quentin's answer says, you use a type trait. 正如昆汀的回答所说,您使用类型特征。 std::is_integral makes sense in your example: std::is_integral在您的示例中很有意义:

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

That doesn't exactly match your comment though. 但这与您的评论不完全一致。 If you really want to have is_integer be true only for int or long then you could define a custom type trait: 如果您确实希望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;
};

Of course, that could be shortened by using the std::is_same trait: 当然,可以通过使用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;
};

You're looking for type traits . 您正在寻找类型特征 std::is_integral might be of interest to you. 您可能会对std::is_integral感兴趣。

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

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