Here is my program that attempts to use std::conditional to set the type of a member variable based on the value of an integer template parameter.
#include <stdio.h>
#include <type_traits>
using namespace std;
class cool{
public:
cool(){ printf("Cool!\n"); }
};
class notcool{
public:
notcool(){ printf("Not cool!\n"); }
};
template<int N>
class myclass{
public:
typedef std::conditional<N==5,cool,notcool> thetype;
thetype theinst;
};
int main(){
printf("Testing\n");
myclass<5> myc5;
myclass<6> myc6;
printf("Done testing\n");
return 0;
}
I would expect my program to give the following output:
Testing
Cool!
Not cool!
Done testing
Instead, the output is
Testing
Done testing
My compiler is GCC 4.9, and the way I compiled this program was using the command g++ test -std=c++11 -o test
Can anyone tell me why the program does not give the output I expect?
typedef typename std::conditional<N==5,cool,notcool>::type thetype;
// ^^^^^^^^ ^^^^^^
thetype
is actually not cool
, and also not notcool
. But std::conditional
.
Yes. std::conditional
is a type, that's how most type traits are implemented. If you want to get the underlying type from the conditional, you need to access the underlying type
member from std::conditional
. That's also how most type traits are implemented: They all have a type
member which can be used to access the actual type you want, and not the type trait type.
In C++14, you would use std::conditional_t
, which is just a alias for the type
member of std::conditional
, but because you are using C++11, you need to access it explicitly:
typedef typename std::conditional<N == 5, cool, notcool>::type thetype;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.