在我的示例中,我有一个类 Foo<T>
.在我的函数中 test
我需要获取 Foo
的模板参数否则为普通类型。首先我开始使用 std::conditional
但是忘记了无论选择哪个模板参数都必须有效。是为 non-Foo
创建类型特化的唯一方法类型?
#include <type_traits>
template <typename TYPE>
class Foo
{
public:
using M = TYPE;
};
template <typename T>
void test(const T& a)
{
// actually I would have used !is_foo<T>::value for the first arg
// but this check is fine to minimise the example
using MY_TYPE = typename std::conditional<
std::is_same<T, int>::value,
T,
typename T::M>::type; // <---Error: error: type 'int' cannot be used prior to '::' because it has no members
}
int main()
{
test(Foo<int>()); // MY_TYPE must be int
test(int()); // MY_TYPE must be int
return 0;
}
最佳答案
好吧,你可以做一个 UnFoo
帮助您获得正确的类型:
template <typename T>
struct UnFoo {
using type = T;
};
template <typename T>
struct UnFoo<Foo<T>> {
using type = T;
};
template <typename T>
void test(const T& a)
{
using MY_TYPE = typename UnFoo<T>::type; //maybe with a helper to get rid of typename
}
另一种选择是为 Foo<T>
编写重载并让它委托(delegate)给其他功能,但这取决于你真正的 test
功能确实如此。
关于c++ - 访问类型成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107013/