【发布时间】:2020-03-12 09:25:33
【问题描述】:
我想编写一个函数,它返回 T 类型的实例,但根据 T 的构造方式,其行为会有所不同。假设我有这样的结构
#include <type_traits>
#include <iostream>
struct A {};
struct B {};
struct C {
C(A a) {
std::cout << "C" << std::endl;
}
};
我想通过给 Cs 一个 A 来创建它们。我有一个类似这样的结构,它使用 enable_if 来选择两个函数之一:
struct E {
template< bool condition = std::is_constructible<C, A>::value,std::enable_if_t<condition,int> = 0>
C get() {
return C{A{}};
}
template< bool condition = std::is_constructible<C, B>::value,std::enable_if_t<condition,bool> = false>
C get() {
return C{B{}};
}
};
这可以用 g++82 编译(我认为也是 g++9),但是 clang9 给了我错误
$ clang++ --std=c++17 main.cpp
main.cpp:26:12: error: no matching constructor for initialization of 'C'
return C{B{}};
^~~~~~
main.cpp:6:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'B' to 'const C' for 1st argument
struct C {
^
main.cpp:6:8: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'B' to 'C' for 1st argument
struct C {
^
main.cpp:7:3: note: candidate constructor not viable: no known conversion from 'B' to 'A' for 1st argument
C(A a) {
^
1 error generated.
即使 enable_if 应该隐藏该功能。 (我打电话给E e; auto c = e.get();)。如果我不对 C 进行硬编码,而是使用模板来传入 C,那么它在两个编译器中都可以工作。
template<typename T>
struct F {
template< bool condition = std::is_constructible<T, A>::value,std::enable_if_t<condition,int> = 0>
T get() {
return T{A{}};
}
template< bool condition = std::is_constructible<T, B>::value,std::enable_if_t<condition,bool> = false>
T get() {
return T{B{}};
}
};
我不明白为什么 clang 显然会对函数的主体进行类型检查,即使该函数应该被 enable_if 禁用。
【问题讨论】: