Is it possible to use conditional statements in a C++ template which could only be "compiled" if the condition is true, otherwise "compilation" is not guaranteed (but the compiler detects it does not need the code anyway, so it will not be included anyway)?
For instance the code below does not compile since the template instantiation
A
k
A
#include <iostream>
struct A {
static constexpr bool value = false;
};
template < typename T >
inline bool f(const T &t) {
if (T::value) {
return t.k; // error: 'const struct A' has no member named 'k'
}
else {
return true;
}
}
int main() {
A a;
std::cout << f(a);
}
Here are two options.
You could use template specialization like so:
template < typename T >
inline bool f(const T &t) {
if (T::value) {
return t.k;
}
else {
return true;
}
}
template <>
inline bool f<A>(const A &t) {
return true;
}
You can use if-constexpr
(C++17) like so:
template < typename T >
inline bool f(const T &t) {
if constexpr (T::value) {
return t.k;
}
else {
return true;
}
}