I have to admit I honestly don't see the fundamental reason to do this, but its your code. Apart from the obvious bug (failure to provide parens for the function call in main()
, and the warning (loss of data converting a char address to int
), the bigger question regarding conditional inclusion is important.
If you have have code such as:
if (something)
{
do something
}
it obviously has to compile, and will not do so conditionally. That the something
is sourced from a non-type template parameter makes no difference. You need to get the logic out of an in-function if-expression and into a template-expansion controlling mechanic instead. Specialization is one such technique, SFINAE is another:
#include <iostream>
#include <iomanip>
#include <type_traits>
#include <cstdint>
static const char* something = "something";
template<class T, bool a>
typename std::enable_if<a>::type f()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
std::cout << something << '\n';
}
template<class T, bool a>
typename std::enable_if<!a>::type f()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
std::cout << std::hex << T(something) << '\n';
}
int main()
{
f<int, true>();
f<intptr_t, false>();
}
Output
typename std::enable_if<a>::type f() [T = int, a = true]
something
typename std::enable_if<!a>::type f() [T = long, a = false]
100001f18
What you do in each is up to you. Of course you could punt and do much/all of this with preprocessor macros, but where's the fun in that?
a
signify in your template parameter list? Why do you need this in the first place? – Oleinelse
condition to be impossible, and is wondering why the compiler doesn't ignore the error since the second template parameter1
will trigger the execution of theif
rather than theelse
statement. – Vibraculum