Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ SFINAE返回型过载_C++_Templates_Sfinae - Fatal编程技术网

C++ SFINAE返回型过载

C++ SFINAE返回型过载,c++,templates,sfinae,C++,Templates,Sfinae,我正在尝试将同一函数的两个重载称为某物。此函数应将另一个函数作为参数,并应根据此另一个函数的返回类型进行重载。到目前为止,我有: #include <iostream> #include <type_traits> using namespace std; unsigned long function1() { return 5; } void function2() { return; } template <typename Algorit

我正在尝试将同一函数的两个重载称为某物。此函数应将另一个函数作为参数,并应根据此另一个函数的返回类型进行重载。到目前为止,我有:

#include <iostream>
#include <type_traits>

using namespace std;

unsigned long function1() {
    return 5;
}
void function2() {
    return;
}

template <typename Algorithm, typename enable_if<is_void<decltype(Algorithm())>::value>::type* = nullptr>
void something(Algorithm a) {
    std::cout << "algorithm returns void\n";
}
template <typename Algorithm, typename enable_if<!is_void<decltype(Algorithm())>::value>::type* = nullptr>
decltype(Algorithm()) something(Algorithm a) {
    std::cout << "algorithm returns non-void: " << a() << "\n";
}

int main() {
    something(function1);
    something(function2);
}
#包括
#包括
使用名称空间std;
无符号长函数1(){
返回5;
}
无效函数2(){
返回;
}
模板
使某物无效(算法a){
标准::cout
decltype(算法())某物(算法a){

std::cout
算法
不调用该函数,而是创建该函数推导类型的实例。您需要另一对括号才能调用它

decltype(Algorithm()())
甚至:

std::declval<Algorithm>()()
std::declval()()

如果您的类型是具有无法访问的默认构造函数的函子。

谢谢,我不知道您可以用这种方式实例化普通函数。如果
算法
是函数类型,或者
自动执行某种操作(算法a)->decltype(a())
,您可以使用这种方法提供可编译的代码吗。
std::declval<Algorithm>()()