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__ << '
';
std::cout << something << '
';
}
template<class T, bool a>
typename std::enable_if<!a>::type f()
{
std::cout << __PRETTY_FUNCTION__ << '
';
std::cout << std::hex << T(something) << '
';
}
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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…