c++ - 回归虚无?

标签 c++ templates c++11 return void

我不明白为什么这段代码编译没有错误:

#include <iostream>

template <class T>
struct Test
{
    static constexpr T f() {return T();} 
};

int main()
{
    Test<void> test;
    test.f(); // Why not an error?
    return 0;
}

按照标准是可以的,还是编译器容忍的?

最佳答案

draft C++11 standard 看起来有效,如果我们看一下5.2.3部分显式类型转换(功能表示法)2段说(强调我的 ):

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case.[...]

措辞非常相似pre C++11也是。

这在 constexpr 中没问题,即使第 7.1.53 说:

The definition of a constexpr function shall satisfy the following constraints:

并包括此项目符号:

its return type shall be a literal type;

and void 不是 C++11 中的 literal 根据 3.9 段落 10但是如果我们再看第6段,它给出了一个适合这种情况的异常(exception),它说:

If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is not a constexpr function or constexpr constructor. [ Note: If the function is a member function it will still be const as described below. —end note ] If no specialization of the template would yield a constexpr function or constexpr constructor, the program is ill-formed; no diagnostic required.

作为凯西 notedC++14 draft standard void 是一个 literal,这是 3.9 部分 Types 段落 10 说:

A type is a literal type if it is:

包括:

— void; or

关于c++ - 回归虚无?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20478193/

相关文章:

c++ - 这是否可以减少免费模板函数的编译时间?

c++ - Qt Model-View框架中如何替换children?

c++ - strstr return 如何不是一个常数

c++ - 如何使用c++11函数回调声明多个模板参数

c++ - 如何为我的类创建数组构造函数?

C++:实现 ln(a) 的数值近似

c++ - 基于模板参数的条件编译时类型映射

c++ - 使用 const 引用的函数模板重载决议

c++ - 仅使用 C++ 中的标准库获取以毫秒为单位的当前日期和时间

C++ shared_ptr use_count for nullptr