带有表达式的C++模板参数

C++ template argument with expression

本文关键字:参数 C++ 表达式      更新时间:2023-10-16

我的C++有问题。我希望能够将表达式作为参数放入模板中。这是我的代码:

#include <vector>
using namespace std;
vector<  ((1>0) ? float : int) > abc() {
}
int main(void){
  return 0;
}

这给了我一个错误:

main.cpp:1:14:14:错误:模板参数1无效
main.cpp:1:14:14:错误:模板参数2无效
main.cpp:11:15:错误:在"{"令牌之前应为不合格的id

最后,我希望能够将1和0替换为whatever,还将float和int替换为typename T和U。为什么它认为有两个参数?我该如何解决这个问题?

(很抱歉,如果这是重复的,我确实仔细寻找了解决方案)

使用std::conditional:

#include <type_traits> 
std::vector<std::conditional<(1 > 0), float, int>::type> abc() {}