【发布时间】:2020-03-08 18:18:13
【问题描述】:
最近我使用concepts 为templated struct 定义不同的构造函数。代码如下:
#include <iostream>
namespace detail {
template<typename T, typename U >
concept SameHelper = std::is_same_v<T, U>;
}
template<typename T, typename U >
concept same_as = detail::SameHelper<T, U> && detail::SameHelper<U, T>;
template<typename T>
concept trivial = same_as<T, bool> || same_as<T, char>;
template<typename T>
concept not_trivial = !trivial<T>;
template<typename T>
struct Foo
{
Foo(T t) requires trivial<T> : member{t} { std::cout << "Foo is trivial" <<std::endl; }
Foo(const auto& t) requires not_trivial<T> : member{t} { std::cout << "Foo is not trivial" <<std::endl;}
const T member;
};
template<typename T>
struct Bar
{
Bar(auto t) requires trivial<T> : member{t} { std::cout << "Bar is trivial" <<std::endl; }
Bar(const T& t) requires not_trivial<T> : member{t} { std::cout << "Bar is not trivial" <<std::endl;}
const T member;
};
template<typename T>
struct Baz
{
Baz(auto t) requires trivial<T> : member{t} { std::cout << "Baz is trivial" <<std::endl; }
Baz(const auto& t) requires not_trivial<T> : member{t} { std::cout << "Baz is not trivial" <<std::endl;}
const T member;
};
template<typename T>
struct Qux
{
Qux(T t) requires trivial<T> : member{t} { std::cout << "Qux is trivial" <<std::endl; }
Qux(const T& t) requires not_trivial<T> : member{t} { std::cout << "Qux is not trivial" <<std::endl;}
const T member;
};
int main()
{
Foo(true);
Foo(3.14159);
Bar(true);
Bar(3.14159);
//Baz(true); // does not compile if uncommented
//Baz(3.14159); // does not compile if uncommented
//Qux(true); // does not compile if uncommented
//Qux(3.14159); // does not compile if uncommented
return 0;
}
You can run the above code online。 我想知道为什么 Foo 和 Bar 编译得很好,而 Baz 和 Qux 如果未注释则不会编译。 恕我直言,Baz 和 Qux 的语法更方便。
【问题讨论】:
-
Foo(3.14159)和Bar(true)都不应该编译... -
@Barry:对不起,我不能跟...为什么不应该
Foo(3.14159)或Bar(true)编译?使用编译器 Clang(主干)函数Foo(3.14159)或Bar(true)进行编译! -
是的,这是一个 Clang 错误。
-
@Barry:感谢您的回答!注意只使用 gcc (trunk)
Qux(true)和Qux(3.14159)编译。我们应该做什么?报告 Clang 错误? -
我回家后会提交一份错误报告。
标签: c++ c++20 c++-concepts