Home > Mobile >  std::conditional_t, How to conditionally define the type of variable when both branches do not compi
std::conditional_t, How to conditionally define the type of variable when both branches do not compi

Time:09-16

I have a templated function which treats 2 types of classes (with old or new format). I want to define a variable that will have its type defined at compile time like:

template <typename T>
using MyType = std::conditional_t<isNewFormatCondition<T>, typename T::subClass::Format, typename T::Format::reference>

template <typename T>
extract(T& t){
  MyType<T> var{t.getFormat()};
}

I mean, For T which is a new classes, var will have type T::subClass::Format, and for old classes it will be a T::Fromat&

More context:

CodePudding user response:

std::conditional_t is not SFINAE, all template arguments must be valid. You can either use SFINAE or simple specialization:

#include <type_traits>
#include <iostream>

template <typename T,bool> 
struct MyType;

template <typename T>
struct MyType<T,false> {
    using type = int;
};

template <typename T>
struct MyType<T,true> {
    using type = double;
};

template <typename T,bool b>
using MyType_t = typename MyType<T,b>::type;

int main() {
    std::cout << std::is_same_v< MyType<void,true>::type, double> << "\n";
    std::cout << std::is_same_v< MyType<void,false>::type, int> << "\n";
}
  • Related