c++ - 使用 `std::conditional_t` 根据其模板参数定义类的 `typedef`

标签 c++ templates c++14

我尝试使用 std::conditional_t 来定义类 Atypedef 依赖于它的模板参数 T :

template< typename T >
class A
{
  public:
    typedef std::conditional_t< std::is_fundamental<T>::value, T, decltype(std::declval<T>().foo())> type;
};

template< typename T >
class B
{
  public:
    T foo()
    {
      // ...
    }
};


int main()
{
  typename A< int >::type a = 5;    // causes an error
  typename A< B<int> >::type b = 5; // does not cause an error

  return 0;
}

不幸的是,代码无法编译。错误:

error: member reference base type 'int' is not a structure or union
        typedef std::conditional_t< std::is_fundamental<T>::value, T, decltype(std::declval<T>().foo())> type;

有人知道怎么解决吗?

最佳答案

条件表达式中的两种类型都必须有效,这不是 SFINAE 上下文。

您可以通过仅“执行”所选的类模板来实现您想要的:

typedef typename std::conditional_t< std::is_fundamental<T>::value, identity<T>, foo_t<T>>::type type;

定义为:

template<typename T>
struct identity{ using type = T; };

template<typename T>
struct foo_t{ using type = decltype(std::declval<T>().foo()); };

demo

关于c++ - 使用 `std::conditional_t` 根据其模板参数定义类的 `typedef`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529543/

相关文章:

c++ - 映射多变量/层系统的泛化

c++ - 错误 : C2988: unrecognizable template declaration/definition

c++ - 如何检查模板参数是否属于特定模板类型(多个类型参数)

c++ - 两个模板类互为成员组成

c++ - 如何通过 std::call_once 使用重载函数

c++ - 不返回 lambda 奇怪的行为

c++ - 并行位置

c++ - 图像稳定

c++ - FFTW 函数 n2fv_64

c++ - 从传递给构造函数的参数类型推导可变成员类型