gpt4 book ai didi

c++ - 为什么 term 不评估一个带 0 个参数的函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:24:15 34 4
gpt4 key购买 nike

当我尝试编译时

template<bool val>
struct boolean { static const bool value = val; };

template<typename T>
struct is_callable : boolean<sizeof((*(T*)0)()) >= 0> { }; // error!

int main(void) { bool b = is_callable<int (*)()>::value; }

我得到:

error C2064: term does not evaluate to a function taking 0 arguments  
see reference to class template instantiation 'is_callable<T>' being compiled

我很确定 int (*)() 可以用 0 参数调用...那么为什么不能编译呢?

最佳答案

问题不在于 int() 的使用。您可以从示例中完全删除它并得到相同的错误。问题是当用作非类型模板参数时 sizeof 表达式本身。示例

template<bool val>
struct boolean { };

template<typename T>
struct is_callable : boolean<sizeof((*(T*)0)()) >= 0> // Error
{
void Test()
{
auto x = sizeof((*(T*)0)()) >= 0; // Compiles
}

};

希望另一个 C++ 人员可以来确定这个 sizeof 表达式作为类型参数是否只是非法的,或者这是否只是 MS C++ 编译器中的一个限制。

关于c++ - 为什么 term 不评估一个带 0 个参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752621/

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