Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template argument with expression

Tags:

c++

templates

I am having trouble with C++. I want to be able to put an expression inside a template as an argument. Here is my code:

#include <vector>
using namespace std;

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

int main(void){
  return 0;
}

This gives me the error:

main.cpp:11:14: error: template argument 1 is invalid
main.cpp:11:14: error: template argument 2 is invalid
main.cpp:11:15: error: expected unqualified-id before ‘{’ token

In the end I want to be able to replace 1 and 0 for whatever and also float and int for typename T and U. Why does it think there are two arguments? And how do I solve this?

(Sorry if this is a duplicate I did have a good look for solutions)
like image 451
Toby Avatar asked Aug 08 '13 05:08

Toby


1 Answers

Use std::conditional:

#include <type_traits> 
std::vector<std::conditional<(1 > 0), float, int>::type> abc() {}
like image 194
chris Avatar answered Oct 29 '22 01:10

chris