条件编译和非类型模板参数 [英] Conditional compilation and non-type template parameters

查看:57
本文介绍了条件编译和非类型模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解非类型模板参数时遇到了麻烦,希望有人能对此有所了解.

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\n";
  } 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");
     ^

但是,编译器无法检测到非类型参数"a"为1,因此将不会采用else分支吗?还是期望太高?在这种情况下,我该如何完成这样的事情?

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?

推荐答案

尝试以下方法:

#include <iostream>
template<typename T, int a>
struct A {
    void f() {
        T("hello");
    }
};

template<typename T>
struct A<T,1> {
    void f() {
        std::cout << "Hello\n";
    }
};


int main() {
  A<int,1> a;
  a.f();
  A<int,2> b;
  b.f();
}

现在,它使用部分模板特化,以便为模板参数的特定值.

Now, this uses partial template specialization in order to provide alternative implementations for specific values of the template parameters.

请注意,我使用了一个类,因为功能模板不能部分专门化

Note that I've used a class, because function templates cannot be partially specialized

这篇关于条件编译和非类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆