Jammanuser
Jammanuser

Reputation: 61

C++ - how does one check if a template class type is void?

I need a way to check if a templated class's type is void.

Here is my attempt:

template <typename target_type, typename start_function_type, typename end_function_type> class C_rule {

  public:
    //...
    void setIntoEffect(bool true_or_false) {
          if (true_or_false == true) {
             for (size_t i = 0; i < targets.size(); i++) {
                 if (typeid(start_function_type) != typeid(void)) {
                    start_function_type start_function_return_value = enforceOnTarget(targets.at(i));
                 }

                 else {
                    enforceOnTarget(targets.at(i));
                 }
             }
          }

          else if ((true_or_false == false) && (is_in_effect == true)) {
             for (size_t i = 0; i < targets.size(); i++) {
                 if (typeid(end_function_type) != typeid(void)) {
                    end_function_type end_function_return_value = removeFromTarget(targets.at(i));
                 }

                 else {
                    removeFromTarget(targets.at(i));
                 }
             }
          }
          is_in_effect = true_or_false;
     }

  protected:
    //...
  private:
    //...

};

However, this generates a compiler error complaining about the two variables "start_function_return_value" and "end_function_return_value" being declared void when created an object of C_rule with "start_function_type" and "end_function_type" being void. I'm trying to prevent creating a variable to store the return value from the 'start' and 'end' functions for the rule, if the return type of those functions is void (since void functions obviously do not return anything). And, as you can see, I'm trying to use the typeid operator for that purpose, but it doesn't appear to be working. Apparently, the if statement is still being entered when the start_function_type and end_function_type is void, and I don't know why. Maybe typeid doesn't work with void? I googled the question, but couldn't find an answer, so that's why I'm asking it here.

Thanks in advance.

Upvotes: 3

Views: 8575

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126432

In C++11, you could use the standard std::is_same<> type trait to verify if two types are the same:

#include <type_traits>

// ...
bool same = std::is_same<T1, T2>::value;

In your case, this could become:

bool same = std::is_same<start_function_type, void>::value;

However, this would not solve your problem, because an if statement is not a compile-time (static) if: both branches of the if statement still have to compile.

What you could do is to specialize your class template for the cases where start_function_type or end_function_type is void, or to factor out the part of the code which deals with them into a separate, specialized class template.

Upvotes: 6

Related Questions