c++ - 访问类型成员

标签 c++ c++11 template-meta-programming typetraits

在我的示例中,我有一个类 Foo<T> .在我的函数中 test我需要获取 Foo 的模板参数否则为普通类型。首先我开始使用 std::conditional但是忘记了无论选择哪个模板参数都必须有效。是为 non-Foo 创建类型特化的唯一方法类型?

Example

#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/

相关文章:

c++ - 如何深度复制 unique_ptr 的 vector

c++ - 'this' 指针的类型

c++ - 你如何使用类型特征来进行条件编译?

c++ - C2712 : Cannot use __try in functions that require object unwinding

C++:是否可以编写一个将不同类型的元素附加到变体数组的函数?

c++ - 没有 __LINE__ 或 __COUNTER__ 宏的唯一模板类

c++ - `inline` , `constexpr` 或 `noexcept` 仅声明函数

c++ - 用于存储数据的结构和外部二进制文件

将捕获作为函数指针的 C++ lambda

c++ - 可以在给定 C++ 类型的情况下实例化对象吗?