Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

c++ - Conditional compilation and non-type template parameters

I am having trouble understanding non-type template arguments and was hoping someone could shed light on this.

#include <iostream>

template<typename T, int a>
void f() {
  if (a == 1) {
    std::cout << "Hello
";
  } else {
    T("hello");
  }
}

int main() {
  f<int, 1>;
}

When I compile this, I get an error saying:

/tmp/conditional_templates.cc:13:12:   required from here
/tmp/conditional_templates.cc:8:5: error: cast from ‘const char*’ to ‘int’ loses precision [-fpermissive]
     T("hello");
     ^

But, can't the compiler detect that the non-type argument "a" is 1 and hence the else branch won't be taken? Or is that too much to expect? In which case, how do I accomplish something like this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...