简体   繁体   English

std::conditional_t, 当两个分支不同时编译时,如何有条件地定义变量的类型?

[英]std::conditional_t, How to conditionally define the type of variable when both branches do not compile at the same time?

I have a templated function which treats 2 types of classes (with old or new format).我有一个模板化的 function 处理 2 种类型的类(具有旧格式或新格式)。 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&我的意思是,对于新类 T,var 的类型为 T::subClass::Format,而对于旧类,它的类型为 T::Fromat&

More context:更多背景:

std::conditional_t is not SFINAE, all template arguments must be valid. std::conditional_t不是 SFINAE,所有模板 arguments 必须有效。 You can either use SFINAE or simple specialization:您可以使用 SFINAE 或简单的专业化:

#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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM