Toby
Toby

Reputation: 416

C++ template argument with expression

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)

Upvotes: 9

Views: 700

Answers (1)

Qaz
Qaz

Reputation: 61930

Use std::conditional:

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

Upvotes: 18

Related Questions