我有一个模板类:
template<typename T>
class Foo
{
X x;
}
对于 Foo< P > 我希望 X 是 int。 对于 Foo< Q >,我希望 X 是 float 的。
我正在 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;
关于c++ - 如何使用 std::conditional 根据模板参数类型设置类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27039035/