【发布时间】:2019-08-23 19:30:32
【问题描述】:
我们考虑使用完全相同的语法创建两种不同类型的目标。这可以通过 lambdas 轻松完成:
auto x = []{};
auto y = []{};
static_assert(!std::is_same_v<decltype(x), decltype(y)>);
但我们不是使用 lambda,而是寻找另一种更优雅的语法。这里有一些测试。我们首先定义一些工具:
#include <iostream>
#include <type_traits>
#define macro object<decltype([]{})>
#define singleton object<decltype([]{})>
constexpr auto function() noexcept
{
return []{};
}
template <class T = decltype([]{})>
constexpr auto defaulted(T arg = {}) noexcept
{
return arg;
}
template <class T = decltype([]{})>
struct object
{
constexpr object() noexcept {}
};
template <class T>
struct ctad
{
template <class... Args>
constexpr ctad(const Args&...) noexcept {}
};
template <class... Args>
ctad(const Args&...) -> ctad<decltype([]{})>;
以及以下变量:
// Lambdas
constexpr auto x0 = []{};
constexpr auto y0 = []{};
constexpr bool ok0 = !std::is_same_v<decltype(x0), decltype(y0)>;
// Function
constexpr auto x1 = function();
constexpr auto y1 = function();
constexpr bool ok1 = !std::is_same_v<decltype(x1), decltype(y1)>;
// Defaulted
constexpr auto x2 = defaulted();
constexpr auto y2 = defaulted();
constexpr bool ok2 = !std::is_same_v<decltype(x2), decltype(y2)>;
// Object
constexpr auto x3 = object();
constexpr auto y3 = object();
constexpr bool ok3 = !std::is_same_v<decltype(x3), decltype(y3)>;
// Ctad
constexpr auto x4 = ctad();
constexpr auto y4 = ctad();
constexpr bool ok4 = !std::is_same_v<decltype(x4), decltype(y4)>;
// Macro
constexpr auto x5 = macro();
constexpr auto y5 = macro();
constexpr bool ok5 = !std::is_same_v<decltype(x5), decltype(y5)>;
// Singleton
constexpr singleton x6;
constexpr singleton y6;
constexpr bool ok6 = !std::is_same_v<decltype(x6), decltype(y6)>;
以及以下测试:
int main(int argc, char* argv[])
{
// Assertions
static_assert(ok0); // lambdas
//static_assert(ok1); // function
static_assert(ok2); // defaulted function
static_assert(ok3); // defaulted class
//static_assert(ok4); // CTAD
static_assert(ok5); // macro
static_assert(ok6); // singleton (macro also)
// Display
std::cout << ok1 << std::endl;
std::cout << ok2 << std::endl;
std::cout << ok3 << std::endl;
std::cout << ok4 << std::endl;
std::cout << ok5 << std::endl;
std::cout << ok6 << std::endl;
// Return
return 0;
}
这是使用当前主干版本的 GCC 编译的,带有选项 -std=c++2a。在编译器资源管理器中查看结果here。
ok0、ok5 和 ok6 工作的事实并不令人意外。然而,ok2 和 ok3 是 true 而 ok4 对我来说并不令人惊讶。
- 有人可以解释使
ok3true但ok4false的规则吗? - 它真的应该如何工作,或者这是一个与实验性功能(未评估上下文中的 lambdas)有关的编译器错误? (非常欢迎参考标准或 C++ 提案)
注意:我真的希望这是一个功能而不是错误,只是因为它可以实现一些疯狂的想法
【问题讨论】:
-
投了赞成票就跑了
-
eel.is/c++draft/temp.arg#8 几乎可以为您提供
ok2/ok3的答案,对于CTAD,构造函数只有一个定义,因此decltype([]{})的单个实例化。 -
hmmm... 几乎看起来像是编译时有状态编程的另一种方式
-
我认为你违反了eel.is/c++draft/temp.res#8.5,但我不确定。
标签: c++ lambda language-lawyer template-meta-programming c++20