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

Tob*_*oby 9 c++ templates

我在使用C++时遇到了麻烦.我希望能够将一个表达式放在模板中作为参数.这是我的代码:

#include <vector>
using namespace std;

vector<  ((1>0) ? float : int) > abc() {
}

int main(void){
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

main.cpp:11:14:错误:模板参数1无效
main.cpp:11:14:错误:模板参数2无效
main.cpp:11:15:错误:预期在'{'令牌之前的unqualified-id

最后,我希望能够替换1和0的任何内容以及typename T和U的float和int.为什么它认为有两个参数?我该如何解决这个问题?

(对不起,如果这是一个副本我确实很好看的解决方案)

chr*_*ris 18

用途std::conditional:

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

  • 您需要围绕`1> 0`的括号,因此编译器会将其解析为条件表达式而不是`vector <std :: conditional <1> ... (2认同)