P i
P i

Reputation: 30744

How to use std::conditional to set type depending on template parameter type

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

http://ideone.com/KzIILu

However, this does not compile.

What's the correct way to do this?

Upvotes: 2

Views: 2955

Answers (1)

ForEveR
ForEveR

Reputation: 55897

You should use compile-time checks, not runtime.

using Xint = typename conditional<is_same<T, P>::value, int, float>::type;

Upvotes: 7

Related Questions