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

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

本文关键字:参数 类型 置类型 何使用 std conditional      更新时间:2023-10-16

>我有一个模板化类:

template<typename T>
class Foo
{
    X x;
}

对于 Foo

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

我正在尝试以下操作:

#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

但是,这不会编译。

正确的方法是什么?

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

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