Matthias
Matthias

Reputation: 4677

Conditional statements in C++ template which could and must only be included by the compiler based on a condition

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 does not have a member named k. However, that part of the code is actually dead code for the template instantiation A.

(The actual use case for this problem: I want to support multiple vertex types for loading meshes. Depending on the Vertex type, certain information will or will not be skipped in the mesh file and indexing unique vertices will also be different.)

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

Upvotes: 2

Views: 95

Answers (1)

Jonas
Jonas

Reputation: 7017

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

Upvotes: 4

Related Questions