使用`std :: conditional_t`来根据其模板参数定义类'typedef`

abr*_*ert 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

有谁知道如何修理它?

krz*_*zaq 5

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

您可以仅“执行”所选的类模板来实现所需的目标:

typedef typename std::conditional_t< std::is_fundamental<T>::value, identity<T>, foo_t<T>>::type type;
Run Code Online (Sandbox Code Playgroud)

定义为:

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

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

演示