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:
- Both types of classes support getFormat().
- Naturally this will not compile as old classes don't have 'subClass::Format' in them, and vice versa
- This question answers the case when both branches of std::conditional compile: How to conditionally declare a local variable based on a template argument?
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";
}