使用函数返回值作为默认模板非类型参数

时间:2015-07-24 00:37:46

标签: c++ templates c++11

这是我的代码:

bool test(){
    return true;
}


template<int asd[], bool T = test()>
void evenprocessor(){
    std::cout<<"this is called"<<std::endl;
};

int asd[] = {1,2,3};

int main(int argc, char** argv) {
    evenprocessor<asd>();
    return 0;
}

我正在为sfinae做一些测试,我很好奇这样的事情是否可行。调用模板后评估函数。我收到一条错误,指出没有匹配函数可以调用evenprocessor

如果在功能或模板参数中使用了函数,我是否做错了或者无法评估函数?像这样:

template<int asd[]>
void evenprocessor(char(*)[test()]){
    std::cout<<"this is called"<<std::endl;
};

int asd[] = {1,2,3};

int main(int argc, char** argv) {
    evenprocessor<asd>();
    return 0;
}

我收到一条错误,指出变量或字段evenprocessor声明为void 。为什么宣布无效?

2 个答案:

答案 0 :(得分:0)

第一个没有为我编译。我不得不把它改成这个,为C ++ 11编译。将test()函数声明为constexpr,让编译器知道可以在编译时对其进行求值。

  

调用模板后评估函数。

您需要确保可以在编译时评估该函数,如前所述。否则你无法编译程序。

#include <iostream>

constexpr bool test(){
        return true;
}


template<int asd[], bool T = test()>
                             void evenprocessor(){
        std::cout << "this is called" << std::endl;
};

int asd[] = {1,2,3};

int main(int argc, char** argv) {
        evenprocessor<asd>();
        return 0;
}

第二个代码示例对我没有意义。你想要实现什么目标?

我看到了几个错误。

  • 参数名称不存在。
  • 函数操作符括号中的代码段应该是lambda函数。您可能尝试实现的是指向一个数组,该数组包含一个bool类型的元素,其值为true。检查您的要求。

答案 1 :(得分:0)

模板非类型参数必须是转换后的常量表达式。调用一个函数“除了constexpr构造函数以外的文字类,constexpr函数,或者一个简单的析构函数的隐式调用”是一个核心常量表达式([expr.const])。在您的演员表中,test() 是核心常量表达式,因为它不是 constexpr。编译错误非常清楚地表明了这一点:

clang的错误:

main.cpp:8:30: error: non-type template argument is not a constant expression
template<int asd[], bool T = test()>
                             ^~~~~~

gcc的错误:

main.cpp:9:6: note:   template argument deduction/substitution failed:
main.cpp:8:34: error: call to non-constexpr function 'bool test()'
 template<int asd[], bool T = test()>
                                  ^

只需修复test

constexpr bool test() {
    return true;
}

第二个例子因同样的原因而失败。数组边界也必须是核心常量表达式。如果您将test()修改为constexpr,那么您的代码会因以下原因而失败:

main.cpp:16:5: error: no matching function for call to 'evenprocessor'
    evenprocessor<asd>();
    ^~~~~~~~~~~~~~~~~~
main.cpp:9:6: note: candidate function template not viable: requires 1 argument, but 0 were provided
void evenprocessor(char(*)[test()]){
     ^

哦,对,要传递一些东西:

evenprocessor<asd>(nullptr);

现在一切都在编译。

相关问题