gpt4 book ai didi

c++ - 如何用sfinae检查,type是否有operator()?

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:00 24 4
gpt4 key购买 nike

我有以下代码:

template <typename T>
struct function_traits
{
typedef decltype(&T::operator()) test_type;
typedef std::true_type res_type;
};

template <typename T>
struct function_traits
{
typedef std::false_type res_type;
};

也就是说,我想知道type有没有operator()。我以为我可以使用 SFINAE 的方式来做到这一点。然而编译器告诉:

'function_traits' : class template has already defined.

这样的代码有什么问题?

P.S.: 这里是简单的用法:

auto f1 = [](const int a){ std::cout << a << std::endl; };
function_traits<decltype(f1)>::res_type;
auto f2 = false;
function_traits<decltype(f2)>::res_type;

编辑:我正在使用 C++ 11 标准

最佳答案

受到积极反馈的鼓舞,我将在此处发布一个简短的答复。

问题是你不能定义一个类两次,但是你定义了两次:-

template <typename T>
struct function_traits { .... some code ..... }

C++ 不允许这样做。

检查一个函数是否存在,已经存在a question关于它,您可以修改它以支持 operator()

这是一个演示,从 Nicola Bonelli's answer 中稍微修改了一下那里。

#include <iostream>

struct Hello
{
void operator()() { }
};

struct Generic {};

// SFINAE test
template <typename T>
class has_parenthesis
{
typedef char one;
typedef long two;

template <typename C> static one test( decltype(&C::operator()) ) ;
template <typename C> static two test(...);

public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

int main(int argc, char *argv[])
{
std::cout << has_parenthesis<Hello>::value << std::endl; //print 1
std::cout << has_parenthesis<Generic>::value << std::endl; //print 0
return 0;
}

我几分钟前才知道它也适用于 operator()

编辑:我将 typeof 更改为 decltype 作为 StoryTellerLmTinyToon 推荐.谢谢。

关于c++ - 如何用sfinae检查,type是否有operator()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42480669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com