我正在使用此处列出的书籍学习 C++ 。特别是,我了解到我们不能用作std::string非类型模板参数。现在,为了进一步明确我对这个主题的概念,我尝试了以下示例,该示例在 gcc 和 msvc 中编译,但在 clang 中不编译。演示
std::string nameOk[] = {"name1", "name2"};
template<std::string &name>
void foo()
{
}
int main()
{
foo<nameOk[0]>(); //this compiles in gcc and msvc but not in clang in C++20
}
Run Code Online (Sandbox Code Playgroud)
我的问题是哪个编译器就在这里(如果有的话)。也就是说,程序是格式良好的还是 IFNDR。
我正在使用此处列出的书籍学习 C++ 。我特别读到了有关可变参数模板的内容。现在,为了进一步阐明我的概念,我还编写了简单的示例,并尝试使用调试器和 cout 语句自己理解它们。
下面给出了一个用 gcc 编译但被 clang 拒绝的程序。演示。
template<typename T, typename... V>
struct C
{
T v(V()...);;
};
int main()
{
C<int> c; //works with gcc but rejected in clang
C<int, double, int, int> c2; //same here: works with gcc but rejected in clang
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是哪个编译器就在这里(如果有的话)?
这是 clang 给出的错误:
<source>:6:12: error: '...' must be innermost component of anonymous pack declaration
T v(V()...);;
^~~
...
1 error generated.
Compiler returned: 1
Run Code Online (Sandbox Code Playgroud) 我正在使用此处列出的书籍学习 C++ 。我编写了以下示例(纯粹出于学术原因),该示例使用 GCC 进行编译,但不使用 Clang 和 MSVC 进行编译。演示。
struct C {
static bool f() noexcept(!noexcept(C::f()))
{
return true;
}
};
Run Code Online (Sandbox Code Playgroud)
正如我们在这里看到的,上面的示例使用 gcc 进行编译,但不使用 msvc 和 clang 进行编译。
所以我的问题是哪个编译器就在这里(如果有的话)。
GCC 编译了这个。
MSVC 说:
<source>(2): fatal error C1202: recursive type or function dependency context too complex
Run Code Online (Sandbox Code Playgroud)
铿锵 说:
<source>:2:40: error: exception specification is not available until end of class definition
static bool f() noexcept(!noexcept(C::f()))
Run Code Online (Sandbox Code Playgroud) 我正在使用此处列出的书籍学习 C++ 。特别是最近学习了使用《C++ Primer》noexcept这本书。现在,为了进一步明确我对这个主题的概念并确认我已经正确理解了事情,我正在编写简单的程序。下面给出了一个这样的程序,它可以使用 MSVC 和 Clang 编译,但不能使用 GCC 编译。演示。
void f() noexcept(5) //accepted by msvc but rejected by gcc
{
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是哪个编译器就在这里(如果有的话)?
以下是一些主要编译器的结果:
| 编译器 | C++版本 | 接受代码 |
|---|---|---|
| 海湾合作委员会 | C++17 | 不 |
| 海湾合作委员会 | C++20 | 不 |
| 铛 | C++17 | 是的 |
| 铛 | C++20 | 不 |
| MSVC | C++17 | 是的 |
| MSVC | C++20 | 是的 |
正如我们所看到的,该程序适用于某些编译器,但不适用于其他编译器。gcc 中的错误说: error: narrowing conversion of '5' from 'int' to 'bool'
c++ exception-specification language-lawyer narrowing noexcept
我正在 C++11 中工作,并有以下可以编译的代码。但问题是func下面示例中的函数也可以使用 a std::function、lambda、函数指针等来调用。
相反,我希望func只能通过指向任何类的非静态成员函数的指针来调用它。也就是说,我想限制这个函数只有成员函数指针。
template <typename Callable, typename... Args> void func(Callable&& callable, Args&&... args)
{
}
struct Test
{
int someMember(int x)
{
return x;
}
};
void g(int, int, int)
{
}
int main()
{
func(g, 1, 1, 1); //this works currently but it should be rejected in the modified program
func([](int){}, 42); //this works currently but it should be rejected in the modified program
Test test;
func(&Test::someMember, test, 1);// this works …Run Code Online (Sandbox Code Playgroud)