Reputation: 31499
My code has the following layout
// A exists only as a true specialization
template<int Boolean>
struct A;
template<>
struct A<1> {};
// B exists only as a false specialization
template<int Boolean>
struct B;
template<>
struct B<0> {};
// then I use it like so
cond ? A<cond> : B<cond>; // actually I want to access an enumeration member value
Doesn't short circuiting apply to the ternary operator? Why do I get a compiler error?
Upvotes: 1
Views: 258
Reputation: 43662
The ternary operator requires you to know the types used in the expression in order to form a common type.
In your case you might use something like (C++11, see std::conditional):
#include <iostream>
#include <typeinfo>
using namespace std;
// A exists only as a true specialization
template<int Boolean>
struct A;
template<>
struct A<1> {
void func() { cout << "A"; }
};
// B exists only as a false specialization
template<int Boolean>
struct B;
template<>
struct B<0> {
void func() { cout << "B"; }
};
int main() {
const bool cond = true;
// std::conditional can provide a compile-time ternary-like evaluation
typedef std::conditional<cond ,A<cond>,B<cond>> myType;
myType::type Obj;
Obj.func();
return 0;
}
Upvotes: 1
Reputation: 62472
The ternary operator requires the true and false expressions to either be the same type, or be collapsable to a common type. Your A
and B
classes have no common type and therefore the expression cannot be resolved to a common type, giving an error.
Upvotes: 1