How to concatenate std :: is_same in a structure

My enable_ifexpression had a very long time, so somehow I wanted a typedef. I'm not sure the best way.

I tried this but it does not work

template<typename T>
struct isValidImageFormat
{
    typedef 
        typename std::is_same<T, float>::value || 
        typename std::is_same<T, unsigned char>::value 
        value;
};

Error:

expected unqualified identifier before the character "||" typename std :: is_same :: value ||

Questions:

  • What is wrong with my code?
  • What would be a good solution to my problem?
+4
source share
4 answers

Do you want std::disjunction(a fantastic word in philosophy for "or"):

typedef std::disjunction<
    std::is_same<T, float>, 
    std::is_same<T, unsigned char>> condition;

Then you can use condition::valueto get the true or false value. Or, if you only need a value, try the following:

constexpr bool condition =
    std::is_same<T, float>::value || 
    std::is_same<T, unsigned char>::value;
+11

typename , , constexpr bool.

template<typename T>
struct isValidImageFormat
{
    constexpr static bool value =  
       std::is_same<T, float>::value || 
       std::is_same<T, unsigned char>::value;
};
+5

Using this method, the result is isValidImageFormat<T>always either std::true_typeeither std::false_type:

#include <utility>
#include <iostream>

template<typename T>
struct isValidImageFormatImpl
{
    static constexpr bool match = std::is_same<T, float>::value
    or std::is_same<T, unsigned char>::value;

    using type = std::conditional_t<match, std::true_type, std::false_type>;
};


template<typename T>
using isValidImageFormat = typename isValidImageFormatImpl<T>::type;

int main()
{
    std::cout << isValidImageFormat<float>() << '\n';
    std::cout << isValidImageFormat<int>() << '\n';

    static_assert(std::is_same<isValidImageFormat<float>, std::true_type>(), "");
    static_assert(std::is_same<isValidImageFormat<int>, std::false_type>(), "");

}

Expected Result:

1
0
+2
source

You really don't need a structure. Starting with C ++ 14, you can easily use a variable template:

#include <type_traits>

template<typename...>
constexpr bool isValidImageFormatVar = false;

template<typename T, typename U, typename... O>
constexpr bool isValidImageFormatVar<T, U, O...> = std::is_same<T, U>::value || isValidImageFormatVar<T, O...>;

template<typename T>
constexpr bool isValidImageFormat = isValidImageFormatVar<T, float, unsigned char>;

int main() {
    static_assert(isValidImageFormat<float>, "!");
    static_assert(isValidImageFormat<unsigned char>, "!");
    static_assert(not isValidImageFormat<int>, "!");
}
+2
source

Source: https://habr.com/ru/post/1656350/


All Articles