gpt4 book ai didi

c++ - 短路模板实例化

转载 作者:行者123 更新时间:2023-11-30 04:08:31 26 4
gpt4 key购买 nike

我的代码有如下布局

// A exists only as a true specialization
template<int Boolean>
struct A;

template<>
struct A<1> {};

// B exists only as a false specialization
template<int Boolean>
struct B;

template<>
struct B<0> {};

// then I use it like so
cond ? A<cond> : B<cond>; // actually I want to access an enumeration member value

短路不适用于三元运算符吗?为什么会出现编译错误?

最佳答案

三元运算符要求您知道表达式中使用的类型,以便形成通用类型。

在您的情况下,您可以使用类似的东西(C++11,参见 std::conditional):

#include <iostream>
#include <typeinfo>
using namespace std;

// A exists only as a true specialization
template<int Boolean>
struct A;

template<>
struct A<1> {
void func() { cout << "A"; }
};

// B exists only as a false specialization
template<int Boolean>
struct B;

template<>
struct B<0> {
void func() { cout << "B"; }
};


int main() {

const bool cond = true;
// std::conditional can provide a compile-time ternary-like evaluation
typedef std::conditional<cond ,A<cond>,B<cond>> myType;

myType::type Obj;
Obj.func();


return 0;
}

http://ideone.com/0Yrcsp

关于c++ - 短路模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21785506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com