[英]How to use std::conditional to set type depending on template parameter type
我有一个模板化的类:
template<typename T>
class Foo
{
X x;
}
对于Foo <P>,我希望X为int。 对于Foo <Q>,我希望X浮动。
我在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;
}
但是,这不会编译。
正确的方法是什么?
您应该使用编译时检查,而不是运行时检查。
using Xint = typename conditional<is_same<T, P>::value, int, float>::type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.