How to write if statements in templates

closed account (Ey80oG1T)
So I have this code:

1
2
3
4
5
6
7
8
9
10
template<typename T, bool = std::is_arithmetic_v<T>>
class Expression;

template <typename T>
class Expression<T, false>
{ };

template <typename T>
class Expression<T, true>
{ };


The first template checks if Expression<type> object is arithmetic or not. If it is, then the second class is called, if not, then the third.

However, I don't want is_arithmetic in there. I want to perform my own checks. For example, check to see if type is int, or char only. So something like this:

1
2
3
4
5
6
7
8
9
10
template<typename T, if(T == int || T == char) return true; else return false;>
class Expression;

template <typename T>
class Expression<T, false>
{ };

template <typename T>
class Expression<T, true>
{ };


How can I do this? Thanks
Last edited on
I'm not entirely sure what you're looking for, but maybe something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <type_traits>

// C++11
template<typename T>
struct Expression : std::integral_constant<bool,
        std::is_same<char, typename std::remove_cv<T>::type>::value ||
        std::is_same<int,  typename std::remove_cv<T>::type>::value >
{};

/* C++17
template<typename T>
struct Expression : std::bool_constant<
        std::is_same_v<char, std::remove_cv_t<T>> ||
        std::is_same_v<int,  std::remove_cv_t<T>> >
{};*/

template< class T >
inline constexpr bool Expression_v = Expression<T>::value;

int main()
{
    std::cout << Expression_v<char> << '\n';
    std::cout << Expression_v<int> << '\n';
    std::cout << Expression_v<const volatile int> << '\n';
    std::cout << Expression_v<unsigned> << '\n';
    std::cout << Expression_v<long> << '\n';
    std::cout << Expression_v<double> << '\n';
}

Last edited on
Topic archived. No new replies allowed.