如何根据模板参数类型使用std :: conditional来设置类型

时间:2020-12-22 16:33:14

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.

对于Foo

,我希望X为int。对于Foo 我希望X是浮动的。

I am attempting the following on ideone:

我在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?

这样做的正确方法是什么?

1 个解决方案

#1


6  

You should use compile-time checks, not runtime.

您应该使用编译时检查,而不是运行时。

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

#1


6  

You should use compile-time checks, not runtime.

您应该使用编译时检查,而不是运行时。

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