Reputation: 30744
I have a templated class:
template<typename T>
class Foo
{
X x;
}
For Foo< P > I wish X to be int. For Foo< Q > I wish X to be float.
I am attempting the following on ideone:
#include <iostream>
#include <typeinfo>
using namespace std;
class P{};
class Q{};
template<typename T>
class Base
{
using Xint = conditional<typeid(T)==typeid(P), int, float>;
Xint x;
public:
void Foo() { cout << typeof(x); }
};
int main() {
Base<P> p; cout << p.Foo() << endl;
Base<Q> q; cout << q.Foo() << endl;
return 0;
}
However, this does not compile.
What's the correct way to do this?
Upvotes: 2
Views: 2955
Reputation: 55897
You should use compile-time checks, not runtime.
using Xint = typename conditional<is_same<T, P>::value, int, float>::type;
Upvotes: 7